Difference between save() and update()

What is the difference between the save() method and the update() method in ActiveRecord.

As save() appears to do the same thing if updating a record using ActiveRecord?

Hi!

As far as I understood you don’t need the update function.

It will be triggered automatically by the save function.

See: app/vendor/yiisoft/yii2/db/BaseActiveRecord.php

And in that file look for the save function.

You will see following comment:




 /**

     * Saves the current record.

     *

     * This method will call [[insert()]] when [[isNewRecord]] is true, or [[update()]]

     * when [[isNewRecord]] is false.

     *

*/



Regards

Even better if you check the source code of save() - https://github.com/yiisoft/yii2/blob/master/framework/db/BaseActiveRecord.php#L590

save() is more practical as you don’t need to know if you are inserting or updating…

my preference is

  • save() for new record

  • update() for update changed attribute values so I know I am updating, not inserting

save() can do what update() can so it is up to you how you want to use them

Ok thanks guys.