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?
My goal si to make history. If some attribute changes, I save a copy into model_history
table.
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
saves the values of the attributes that were changed.
You need to check for dirty attributes
You can call yii\\db\\ActiveRecord::getDirtyAttributes()
to get the attributes that are currently dirty.
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#dirty-attributes
You must be careful,by use dirtyAttributes property because yii, consider the following: before myfield type int =4 after myfield type string = "4" if it happens myfield will be into dirtyAttributes automatically.
Other point: For your dirtyAttributes your fields should be "safeAttributes" in the scenario where you are going to work, in other way this changes will be ignored
regards
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.