0

我正在使用 cakePHP 为什么不将名称插入表中,当表更新但没有名称时要传递一个空值接缝?

数据库中的表

CREATE TABLE tests (
id serial not null unique primary key,
name varchar,
created timestamp default CURRENT_TIMESTAMP

) 

添加.ctp

<?php
echo $this->Form->create('Post');
echo $this->Form->input('name');
echo $this->Form->end('RSVP');
?>

测试模型

<?php
class Test extends AppModel {
var $name = 'Test';
}

测试控制器

<?php
class TestController extends AppController {
public $helpers = array('Html', 'Form');

var $name = "Test";


public function index() {
    $this->set('tests', $this->Test->find('all'));
}

public function view($id = null) {
    $this->Test->id = $id;
    $this->set('Test', $this->Test->read());
}

public function add() {
    if ($this->request->is('post')) {
        if ($this->Test->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } 
        else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}

public function edit($id = null) {
    $this->Test->id = $id;
    if ($this->request->is('get')) {
        $this->request->data = $this->Post->read();
    } 
    else {
        if ($this->Test->save($this->request->data)) {
            $this->Session->setFlash('Your post has been updated.');
            $this->redirect(array('action' => 'index'));
        } 
        else {
            $this->Session->setFlash('Unable to update your post.');
        }
    }
}

public function delete($id) {
        if ($this->request->is('get')) {
            throw new MethodNotAllowedException();
        }
        if ($this->Test->delete($id)) {
            $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
            $this->redirect(array('action' => 'index'));
        }
    }
}
4

1 回答 1

1

在您的方法中,您错过了 include $this->Test->create();,这将向表中添加新行并在其中插入新数据。

public function add() {
    if ($this->request->is('post')) {
        $this->Test->create(); // missed this line
        if ($this->Test->save($this->request->data)) {
            $this->Session->setFlash('Your post has been saved.');
            $this->redirect(array('action' => 'index'));
        } 
        else {
            $this->Session->setFlash('Unable to add your post.');
        }
    }
}
于 2012-05-03T09:48:28.130 回答