我的模型,如果模型的特定属性的改变只应被解雇的beforeSave养的Yii事件。的Yii上更新,检测一个特定的AR属性已在beforeSave改变()
我能想到的是如何做到这一点在目前的唯一方法是通过创建一个新的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()
的新本地属性中?
的这的确是唯一的“干净”的方式做到这一点Yii中。我所做的是实现派生的ActiveRecord,该功能内置了该功能,并使其可用于我的所有模型。每次再做一次都要容易得多。我也给了它像“getIsChanged()”和“getChangedProperties()”等方法。 – Blizz