Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

yii2

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.

like image 387
Sherin Jose Avatar asked Sep 21 '25 12:09

Sherin Jose


2 Answers

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))
like image 98
Maksym Semenykhin Avatar answered Sep 23 '25 19:09

Maksym Semenykhin


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);
like image 28
Yasin Patel Avatar answered Sep 23 '25 19:09

Yasin Patel