Create Update On Duplicate Query

I want to create a query that insert a record in my table and update it if its id exist:

what i did is a query to select the record of specific id if the select statement is empty it will insert the data otherwise update, but i think there is a better way to do this in yii2.

can any one help me ?

what is the purpose of doing so? and what are you updating any counter values or others?

Something like this:

public function update($id, $name) {

   $model = ModelClass::findOne($id);

   if ($model == null) {

        $model = new ModelClass;

        $model->id = $id;

        $model->name = $name;


   else {

       $model->name = $name;


   if ($model->save()) {

      return 'success';


   return 'error';


Then call that function wherever you need.

1 Like

just to reduce numbers of queries, write one query instead of three queries.

there are only more ugly ways as far as I see. When you have to do a great amout of queries and use MySQL the REPLACE command may help you but the best solution for yii is what has been described here.

This is perfect! Thanks!