Sherin Jose
Sherin Jose

Reputation: 2516

Yii2 delete all rows based on an equal to condition and a not in condition

Here I am using Yii2 for developing an application. It is slightly different from Yii1. During the development, I am just stuck on a point that I need a delete functionality for an area. For deleting some rows from DB I am using deleteAll() method like the following:

Model::deleteAll(['not in', '<attribute_1>', $attribute_1_values_array]);

It is working fine for me. But now I want to append another condition to this delete function like:

<attribute_2>=<attribute_2_value>

I know we can use where() for adding conditions with delete() and then I tried it with this deleteAll() method. But it didn't support.

Here I need to combine both not in condition and equal to condition in the same query.

Any help will be appreciated.

Upvotes: 4

Views: 15187

Answers (3)

Yasin Patel
Yasin Patel

Reputation: 5731

You can delete all records as below :

Model::deleteAll(
          ['AND',
            ['NOT',['attribute_1'=>$attribute_1_values_array]],  // array i.e [1,2]
            ['attribute_2'=> $attribute_2_value ]
          ]
        );

Compact way :

$condition = ['AND',
  ['NOT',['attribute_1'=>$attribute_1_values_array]],
  ['attribute_2'=> $attribute_2_value ]
];

Model::deleteAll($condition);

Upvotes: 5

Husnain Aslam
Husnain Aslam

Reputation: 865

You can remove [] brackets from deleteAll() function and use like this.

Model::deleteAll('attribute_1 NOT IN :attr_1_value AND attribute_2 = :attr_2_value', ['attr_1_value'=>$attribute_1_values_array,':attr_2_value'=>$attribute_2_value]);

OR

Model::deleteAll('attribute_1 NOT IN '.$attribute_1_values_array.' AND attribute_2 = '.$attribute_2_value);

Removing [] will allow adding standard/custom query.

Upvotes: 4

Maksym Semenykhin
Maksym Semenykhin

Reputation: 1945

here is how I usually do this :

\common\models\Record::deleteAll([
    'AND', 'status = :attribute_2', [
        'NOT IN', 'id',
        [1, 2]
    ]
    ], [
    ':attribute_2' => 'new'
]);

and the result is :

DELETE FROM `record` WHERE (status = 'new') AND (`id` NOT IN (1, 2))

Upvotes: 9

Related Questions