【问题标题】:What will happen, if Model::$id will not be cleared by create()?如果 Model::$id 不会被 create() 清除,会发生什么?
【发布时间】:2014-03-05 08:00:44
【问题描述】:

在 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.'));
    }
}

我不太明白 Cookbook 中描述的$this->Post->create(); 的目的:

[...]它重置模型状态以保存新信息。它不是 实际上在数据库中创建了一条记录,但清除了 Model::$id [...]

(发现于Cookbook 2.x)

如果 create(); 不清除 Model::$id 会发生什么?

【问题讨论】:

  • 我不明白这个问题What will happen, if Model::$id will not be cleared by create();? - 你是问它是否会被清除? (是的,会的)
  • @AD78six:感谢您的评论。当我删除行 $this->Post->create(); 时,我的帖子也会被保存。那我为什么不把它排除在外呢?
  • 它只是确保模型处于干净状态。你可以忽略它,但保持它是一个好习惯。
  • @AD7six:我可以想象,在某些情况下你必须清理模型。谢谢。

标签: cakephp cakephp-2.3


【解决方案1】:

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

我可以在这个代码示例中省略创建调用吗:

是的,是的,你可以

Model::create 将模型重置为一致状态,删除 data 属性并将 id 重置为 null。

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

【讨论】:

  • 非常好 - 有道理。
【解决方案2】:

根据您在问题中提供的代码,您可以删除 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。在第二次执行时,因为我们没有清除 Model::$id,它会更新标题为“Title two”的记录,而不是将其作为新记录插入,依此类推。 最后,您将只获得一条 id 为 21 的记录,其标题值为“标题三”。

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 2016-09-14
    相关资源
    最近更新 更多