php - 即使记录是新的,Yii 如何使用模型更新

标签 php mysql performance yii

我有一个非常重要的系统,它尽可能接近实时。 出于这个原因,当我从外部源获取数据时,我想使用 $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;
}

最佳答案

$model->save

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

As we can see, we use the same save() method to perform insertion and updating operations. If an AR instance is created using the new operator, calling save() would insert a new row into the database table; if the AR instance is the result of some find or findAll method call, calling save() would update the existing row in the table.

关于php - 即使记录是新的,Yii 如何使用模型更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16336466/

相关文章:

php - 使用 mysql 和 PHP 为日历应用程序进行条件选择

php - 使用 PHP 和 Curl 登录我的网站表单

PHP 错误 - 在非对象上调用成员函数 execute()

php - PHP 和 MySQL 中嵌套数组的输出/结构出现问题

c - 矩阵旋转的性能优化

php - MySQL降序问题

php - MySQL 中的阿拉伯字符问题

mysql - mysql中递归查询的更好方法

java - 在 switch 语句内循环或在循环内使用 switch 语句更有效?

algorithm - 哈希表真的可以是 O(1) 吗?