基本CakePHP:编辑帖子方法成为添加帖子方法

时间:2015-06-17 08:37:29

标签: cakephp methods sql-update edit

目前关注博客教程,但我的数据库及其变量不同。

我正在浏览“编辑帖子”方法并按照他们给出的步骤操作,但他们会变成“添加帖子”方法。

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

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 Query

  

SQL查询:INSERT INTO fyp_seatmanagmentdateofevent   (eventDate_idevent_datemodified)VALUES(45,'2015-06-10',   '2015-06-17 10:19:45')

1 个答案:

答案 0 :(得分:1)

您没有使用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);