Cakephp 如果create()不清除Model::$id,会发生什么情况?

Cakephp 如果create()不清除Model::$id,会发生什么情况?,cakephp,cakephp-2.3,Cakephp,Cakephp 2.3,在CakePHPs博客教程中,将通过以下操作保存一篇文章: public function add() { if ($this->request->is('post')) { $this->Post->create(); if ($this->Post->save($this->request->data)) { $this->Session->

在CakePHPs博客教程中,将通过以下操作保存一篇文章:

public function add() 
{
    if ($this->request->is('post')) 
    {
        $this->Post->create();
        if ($this->Post->save($this->request->data)) 
        {
            $this->Session->setFlash(__('Your post has been saved.'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Unable to add your post.'));
    }
}
我不太明白
$this->Post->create()的目的在烹饪手册中描述:

[…]它重置模型状态以保存新信息。事实并非如此 实际在数据库中创建记录,但清除模型::$id[…]

(位于)


如果模型::$id不会被
create()清除,会发生什么

我理解你的问题(现在)的意思是:

在这个代码示例中,我是否可以省略create调用:

是的,是的,你可以 将模型重置为一致状态,删除数据属性并将id重置为null


此方法仅在模型已修改的情况下执行某些操作;如果模型状态没有被修改,或者它是一个动作的第一个被调用的方法,那么它不会做任何事情-但是,当现有模型状态与下一个模型方法调用不相关时,总是调用
create
是一个好习惯,可以防止意外的应用程序错误。

根据您在问题中提供的代码,您可以删除Model::create()。它不会影响数据插入

但在循环中插入记录时,清除Model::$id很重要。因为如果不这样做,只会插入一条记录,并用下一条记录覆盖

比如说,

$posts = array(
    0 => array(
        'title' => "Title one"
    ),
    1 => array(
        'title' => "Title two"
    ),
    2 => array(
        'title' => "Title three"
    )
);

foreach($posts as $post) {
    $this->Post->create(); // Or you can use $this->Post->id = null;
    $this->Post->save($post);
}
如果删除$this->Post->create(),在第一次执行时,它将插入一条标题为“title one”的新记录,并将最后一次插入id设置为Model::$id,例如21。在第二次执行时,由于我们尚未清除模型::$id,它将使用标题“title two”更新记录,而不是将其作为新记录插入,依此类推。 最后,您将只获得一条id为21的记录,其标题值将为“title three”

这只是一个例子,有其他方法可以保存多个记录而不循环


希望这会有所帮助。

我不明白这个问题
如果模型::$id不会被create()清除,会发生什么-您是否在询问是否将清除?@AD78six:谢谢你的评论。当我删除行
$this->Post->create()时我的帖子也将被保存。那么为什么我不应该忽略它呢?它只是确保模型处于干净状态。你可以省去它,但保持它是一个好习惯。@AD7six:我可以想象,在某些情况下,你必须清洁模型。谢谢。非常好-有道理。