【发布时间】:2013-08-27 09:16:36
【问题描述】:
我在模型的 beforeSave 上引发了一个 Yii 事件,只有在模型的特定属性发生更改时才会触发该事件。
目前我能想到的唯一方法是创建一个新的 AR 对象并使用当前 PK 查询旧模型的数据库,但这并没有得到很好的优化。
这就是我现在所拥有的(请注意,我的表没有 PK,这就是我查询所有属性的原因,除了我要比较的属性 - 因此是 unset 函数):
public function beforeSave()
{
if(!$this->isNewRecord){ // only when a record is modified
$newAttributes = $this->attributes;
unset($newAttributes['level']);
$oldModel = self::model()->findByAttributes($newAttributes);
if($oldModel->level != $this->level)
// Raising event here
}
return parent::beforeSave();
}
有没有更好的方法?也许将旧属性存储在 afterFind() 的新本地属性中?
【问题讨论】:
标签: php yii before-save