【问题标题】:Yii how to use model update even if the record is newYii 即使记录是新的,如何使用模型更新
【发布时间】:2013-05-02 11:06:29
【问题描述】:

我有一个尽可能接近实时的系统,这一点非常重要。 因此,当我从外部源获取数据时,我想使用 $model->update 而不是执行 2 个查询:

$model->find()
if(new)
    $model->save
else
    $model->update

这太费时间了...我可以使用 $model->update 吗?如果记录是新的,它会简单地创建它吗?

我查看了更新代码,但我不确定如何覆盖它。

public function update($attributes=null)
{
    if($this->getIsNewRecord())
        throw new CDbException(Yii::t('yii','The active record cannot be updated because it is new.'));
    if($this->beforeSave())
    {
        Yii::trace(get_class($this).'.update()','system.db.ar.CActiveRecord');
        if($this->_pk===null)
            $this->_pk=$this->getPrimaryKey();
        $this->updateByPk($this->getOldPrimaryKey(),$this->getAttributes($attributes));
        $this->_pk=$this->getPrimaryKey();
        $this->afterSave();
        return true;
    }
    else
        return false;
}

【问题讨论】:

  • 太耗时?为什么?时间究竟花在了哪里?
  • 不可能将任何 CRUD 语句“组合”或不需要另一个。你不能对数据库说Make a new record in the table by updating a not existing one。您不能将INSERT INTO <table>UPDATE <table> WHERE 混淆。您受到常规数据库查询语言的限制。但是:正如下面http://stackoverflow.com/a/16336521/431967 的答案中所述,您只需执行 $model->save()。

标签: php mysql performance yii


【解决方案1】:
$model->save

按照您想要的方式工作。如果模型是新的,它将插入,如果模型存在,它将更新。 http://www.yiiframework.com/doc/guide/1.1/en/database.ar#updating-record

我们可以看到,我们使用相同的 save() 方法来执行插入和 更新操作。如果使用新创建的 AR 实例 运算符,调用 save() 会将新行插入数据库 桌子;如果 AR 实例是某个 find 或 findAll 方法的结果 调用,调用 save() 将更新表中的现有行。

【讨论】:

  • 不幸的是 model->save 将保存每条记录并且不会更新,因为我每次都在循环并创建一个新模型......但根据这里的答案,我明白这是我必须做的做。
  • 如果您确定它是现有模型,您可以将 isNewRecord 设置为 false。然后 save() 将执行更新。或者使用 ActiveRecord::update() 方法。但是你将没有验证。
  • @DannyValariola 它每次都会插入,因为您的数据库中没有唯一键,否则它如何知道模型存在。
【解决方案2】:

什么都不用做

$model->isNewRecord 会在执行查询之前检查记录是否是新的。

如果 $model->isNewRecord 返回 "true",$model->save 将创建新记录,

如果它返回 "false" $model->save 将根据主键更新记录。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多