Yii2 Insert and Ignore duplicates

March 28, 2019 , ,

One of the things that comes with learning a framework is that we should change a bit the way we work in order to correctly build an app.

One of the frameworks I’ve used the most (on a personal and professional level) is Yii2 and my experience has been excellent – fast, reliable and well maintained.

One of the pain points I got since the beginning is the way the database interaction system works that in the end is quite simple, but only now that I understand it. One of the situations that I had to solve was how to do an Insert/Update, so below here’s a snippet on how to do it.


$model::YourModel::findOne(ID); // findOne() searches for the table key, you can use find()->where(‘=’, ‘column’, ‘name’)->one(); to identify the model.

$model = new YourModel;

$model->column_1 = ‘text’;
$model->column_2 = 123;

The logic is:

  • You try to find if you already have the item in the Databse by calling the findOne(key);
  • If there’s no model, create it from scratch;
  • Assign values to the fields
  • Save

That should really be it, I’m surprised there’s no other documentation explaining this quickly and simple.

Feel free to post any questions below.