Sobes.tech
Junior — Middle

Is the save() method called automatically when saving a model in Yii2?

sobes.tech AI

Answer from AI

In Yii2, the save() method of a model does not run automatically when saving — on the contrary, it is the call to the save() method that initiates the process of saving the model to the database.

When you call $model->save(), the following happens inside this method:

  • Validation of the model data (if enabled)
  • Calling the beforeSave and afterSave events
  • Executing an SQL INSERT or UPDATE query

Thus, save() is the main method that must be explicitly called to save the model.

Example:

$model = new User();
$model->username = 'ivan';
$model->save(); // saves the model to the database