Yii2 保存前检查属性是否更改 [英] Yii2 before save check if attributes are changed

查看:31
本文介绍了Yii2 保存前检查属性是否更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据存储在数据库中的数据检查我的模型中的某些属性是否在 beforeSave() 方法中发生了变化.

I want to check if some attributes in my model are changed in beforeSave() method according to data stored in database.

是否有一些最佳实践可以检查模型是否已更改?

Is there some best practice to check if model has changed?

我的目标是创造历史.如果某些属性发生更改,我会将副本保存到 model_history 表中.

My goal si to make history. If some attribute changes, I save a copy into model_history table.

推荐答案

您实际上可以使用 afterSave() 做到这一点.

You can actually do that using afterSave().

public function afterSave($insert, $changedAttributes) {
    parent::afterSave($insert, $changedAttributes);
    if(!$insert) {
        // your code here like $changedAttributes['myField'];
    }
}

$changedAttributes 保存已更改的属性值.

$changedAttributes saves the values of the attributes that were changed.

这篇关于Yii2 保存前检查属性是否更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆