【发布时间】: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