基本 CakePHP:编辑 Post 方法变为添加 Post 方法

Basic CakePHP: Edit Post Method become Add Post Method

目前正在按照博客教程进行操作,但是我的数据库和它们的变量不同。

我正在查看 "Edit Post" 方法并按照他们给出的步骤进行操作,但是他们变成了 "Add Post" 方法。

是什么原因造成的? (我已经将视图传递的隐藏字段设置为控制器,但是它们会显示错误 Error: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '45' for key 'PRIMARY' 因为它们执行的是插入语句而不是更新)。

DateOfEventController.php

public function edit($id = null) {
    //Retrieve from database
    $post = $this->dateofevent->findByeventdateId($id);
    debug($post);    

    //Without Id
    if (!$id) {
        throw new NotFoundException(__('Invalid post'));
    }

    //If  Not Exist the id
    if (!$post) {
        throw new NotFoundException(__('Invalid post'));
    }

    //After press the submit
    if ($this->request->is(array('post','put'))) {
        echo "yo";
        $this->dateofevent->eventDate_id = $id;
        if ($this->dateofevent->save($this->request->data)) {
            $this->Session->setFlash(__('Your post has been updated.'));
           // return $this->redirect(array('action' => 'index'));
        }

        else{$this->Session->setFlash(__('Unable to update your post.'));}
    }

    //Set the data same as retrieved
    if (!$this->request->data) { $this->request->data = $post;}
}

edit.ctp

<?php
echo $this->Form->create('dateofevent');
//echo $this->Form->input('eventDate_id', array('type' => 'hidden'));
echo $this->Form->hidden('eventDate_id');
echo $this->Form->input('event_date',array(
    'label' => 'Event Date',
    'type' => 'text',
    'id' => 'datepicker'));
echo $this->Form->end('Save Post');
?>

Sql查询

SQL Query: INSERT INTO fyp_seatmanagment.dateofevent (eventDate_id, event_date, modified) VALUES (45, '2015-06-10', '2015-06-17 10:19:45')

您没有使用 Cake 的标准命名约定,因此您需要确保覆盖 Cake 通常会自动生成的模型属性。 Cake 期望 primaryKeyid,它使用它来确定是 insert 还是 update 一条记录。当您使用 eventDate_id 时,您需要在 your model 中告诉 Cake:-

class DateOfEvent extends AppModel {
    public $primaryKey = 'eventDate_id';
}

除非有特殊原因导致您不能使用 Cake 的命名约定,否则您应该这样做。使用您自己的命名约定会给您带来更多的工作和问题。

我还注意到您在控制器中错误地使用驼峰式大小写方法和变量名称,这可能会导致问题。例如 $post = $this->dateofevent->findByeventdateId($id) 应该是:-

$post = $this->DateOfEvent->findByEventdateId($id);