35

What is the active Record way of adding IN condition to an active Query in yii 1.x you could use CDbCriteria like this

$cr = new CDbCriteria();
$cr->addNotInCondition('attribute', $array);

There seem to be no equivalent API call in yii2 active record implementation, how to do this via active record ?

Manquer
  • 7,390
  • 8
  • 42
  • 69
  • this [link](http://stackoverflow.com/questions/31041546/how-to-use-not-equal-to-inside-a-yii2-query/32860991#32860991) may help someone. – Muhammad Shahzad Apr 07 '16 at 12:32

4 Answers4

84

Well all query operands seems now merged within in yii\db\QueryInterface::Where() per documentation an In condition can now be added using something like

$query = MyModel::find()->where(['attribute'=>$array]);

for a not In condition it is slightly different format

$query = MyModel::find()->where(['not in','attribute',$array]);
Mihai P.
  • 9,307
  • 3
  • 38
  • 49
Manquer
  • 7,390
  • 8
  • 42
  • 69
  • 3
    This will fail, we need: $query = MyModel::find()->where(['attribute'=>$array])->all(); – Billy Dec 07 '15 at 20:07
  • that would be for an in condition, the question is about not in refer here for details: http://www.yiiframework.com/doc-2.0/yii-db-query.html#where()-detail – Manquer Dec 07 '15 at 20:19
  • what is `$array` in the query ? – Moeez Apr 13 '18 at 06:57
5
$query = MyModel::findAll(['not in ','attribute',$array]);

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

Oleg Ozimok
  • 259
  • 2
  • 4
3

For numbers:

$query = MyModel::find()->where('NOT IN('.implode(',', $array).')');

For strings

$deleteContracts = Contract::find()
    ->where([
        'session_id' => $session_id,
        'status' => Contract::STATUS_COMPLETED
    ])
    ->andWhere(['not in', 'contract_id', $contracts])
    ->all();
1

For me the only working solution was :

$query = MyModel::find()->where('`your-attribute` NOT IN(' . implode(',', $array) . ')')->all();
medskill
  • 320
  • 3
  • 13