Yii on update,检测onSave()上是否更改了特定的AR属性

Dzh*_*eyt 7 php yii before-save

我在模型的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();
}
Run Code Online (Sandbox Code Playgroud)

有更好的方法吗?也许将旧属性存储在新的本地属性中afterFind()

Dzh*_*eyt 14

您需要将旧属性存储在AR类的本地属性中,以便您可以随时将当前属性与旧属性进行比较.

第1步.向AR类添加新属性:

// Stores old attributes on afterFind() so we can compare
// against them before/after save
protected $oldAttributes;
Run Code Online (Sandbox Code Playgroud)

第2步.覆盖Yii afterFind()并在检索原始属性后立即存储它们.

public function afterFind(){
    $this->oldAttributes = $this->attributes;
    return parent::afterFind();
}
Run Code Online (Sandbox Code Playgroud)

第3步.比较beforeSave/afterSaveAR类中您喜欢的新旧属性.在下面的示例中,我们将检查名为"level"的属性是否已更改.

public function beforeSave()
{
    if(isset($this->oldAttributes['level']) && $this->level != $this->oldAttributes['level']){

            // The attribute is changed. Do something here...

    }

    return parent::beforeSave();
}
Run Code Online (Sandbox Code Playgroud)