Yii2 before saving check if attributes are changed

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

Is there any best practice to check if the model has changed?

My goal is si to make a story. If any attribute changes, I save a copy in the table model_history.

+4
source share
2 answers

You can do this with afterSave().

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

$changedAttributes saves attribute values ​​that have been changed.

+4
source

You need to check for dirty attributes

yii\db\ActiveRecord::getDirtyAttributes(), , .

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#dirty-attributes

+2

Source: https://habr.com/ru/post/1670971/


All Articles