K
K
knowledge2019-04-01 21:15:34
Yii
knowledge, 2019-04-01 21:15:34

Will the entry in the db be updated in yii?

Tell me if the record in the database will be updated in such a construction if the data remains the same
In the database
User
id=1
name='john'
age=29
In the code
$user = User::find(1):
$user->name= 'john'
$user->age=29
$user->save():
Will the database be updated?
If yes, is there any way to disable it?
A large number of models are being updated, some data in some models has been updated, in some it has not.
If not updated, I would not want to write it down again

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry, 2019-04-01
@knowledge

Good evening.
Check oldAttributes() . If they match the new attributes, then abort the script. If they don't match, update.
In the update action, you can do this check

if(empty($model->getDirtyAttributes())){
                // если данные не обновляются, то делайте что Вы желаете)))
            }

D
Denis, 2019-04-01
@sidni

In theory, it shouldn’t (for accuracy, you can check if the request was debuggered) in uii2 there is a dirty-attributes check and if the attribute has not changed its value and type, then it is not dirty

M
Mysterion, 2019-04-01
@Mysterion

Yes, they will be updated. Moreover, in yii, if we are talking about the first version of the framework, there is an unpleasant feature - if you get a record from the database through an active record, change only one field and save the record again, then a request with an update of all fields will go to the database, but only one thing will change.
You can avoid, for example, by comparing the fields and values ​​in the controller, if we are talking about a small number of fields and a temporary solution, or adding afterFind and beforeSave methods to the model. Save in afterFind $this->attributes to some private variable and in beforeSave check $this->attributes with the value of this variable.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question