Sobes.tech
Junior — Middle

Is the insert() method activated when adding a new record to the database in Yii2?

sobes.tech AI

Answer from AI

In Yii2, the insert() method is activated when you explicitly call it to add a new record to the database via ActiveRecord. When $model->insert() is called, a new record is inserted, and this method returns true upon successful execution.

However, if you use the save() method, Yii2 itself decides whether to call insert() or update(): if the model is new (isNewRecord == true), then insert() is called; otherwise, update() is called.

Example:

$model = new Post();
$model->title = 'New record';
$model->content = 'Text';
$model->insert(); // explicitly inserting a new record

// or
$model->save(); // will automatically call insert() if the model is new

Thus, the insert() method is indeed activated when adding a new record, whether you call it directly or through save() for a new model.