【问题标题】:edit form adds new insert in cakePHP编辑表单在 cakePHP 中添加新的插入
【发布时间】:2014-04-19 21:11:46
【问题描述】:

我在 post 表中有 'c_id' 而不是 'id'

这是我的控制器

public function editContact( $id = null ) {

    if( !$id ) {
        throw new NotFoundException( __( 'Invalid Post' ) );
    }

    $contact = $this->Contact->findBycId( $id );
    if( !$contact ) {
        throw new NotFoundException( __( 'Invalid Post' ) );
    }


    if( $this->request->is( array( 'post', 'put' ) ) ) {
        $this->Contact->id = $id;
        //echo $this->Contact->cid;
        if( $this->Contact->save( $this->request->data ) ) {
            $this->Session->setFlash( __( 'Data Updated' ) );
            return $this->redirect( array( 'action' => 'index' ) );
        }
        $this->Session->setFlash( __( 'Unable To update Data!' ) );
    }

    if( !$this->request->data ) {
        $this->request->data = $contact;
    }
}

我收到了这个错误

数据库错误 错误:SQLSTATE [42S22]:找不到列:1054 'where 子句'中的未知列 'Contact.id'

SQL 查询:SELECT COUNT(*) AS count FROM learnin_cakePHP.contacts AS Contact WHERE Contact.id = '19'

但是当我改变这一行时

$this->Contact->id = $id;

$this->Contact->cid = $c_id; 

它作为新记录插入。

在我的编辑表单中有:

<input type="hidden" value="POST" name="_method">

我发现 VALUE 必须是 PUT 而不是 POST

【问题讨论】:

    标签: cakephp insert-update


    【解决方案1】:

    确保你的模型有

    public $primaryKey = 'c_id';
    

    在控制器中,使用

    if ($this->request->is(array('post', 'put'))) {
        $this->Contact->id = $id;
        if( $this->Contact->save($this->request->data)) {
           // ...
        }
    }
    

    【讨论】:

    【解决方案2】:

    primaryKey 添加到 Contact.php:

    public $primaryKey = 'c_id';
    

    【讨论】:

    • 我添加了 public $primaryKey = 'c_id';在 Contact.php 模型中,但仍然无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多