0

I am working on yii2. I am using active record for searching a reference number. The query is below

$q = isset($_GET['q']) ? $_GET['q'] : '';
    if(empty($q)) exit;
    $ser = Survey::find()->where("ref_no like '%$q%'")->andWhere(['status'=>1])->asArray()->all();

    return json_encode($ser);

The above query will get all the reference numbers which are in survey table. Now I want to add a NOT IN condition. The raw query is below

...... where ref_no LIKE '%$q%' NOT IN (select ref_no from installations where ref_no LIKE '%q%')

How can I add this to my active record query?

Any help would be highly appreciated.

Moeez
  • 494
  • 9
  • 55
  • 147
  • 1
    Possible duplicate of [Yii2 subquery in Active Record](https://stackoverflow.com/questions/30164491/yii2-subquery-in-active-record) – Sfili_81 Apr 13 '18 at 06:57

2 Answers2

2

You can use subquery for this too (assuming your installation table i related to Installations model)

  $subQuery = Installations::find()->select('ref_no')->where("ref_no like '%$q%'");
  $query = Survey::find()->where(['not in', 'ref_no', $subQuery]);
  $models = $query->all();                         
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

Change Your Query as Below :

$ser = Survey::find()->where("ref_no like '%$q%'")
->andWhere(['status'=>1])
->andWhere("ref_no NOT IN (select ref_no from installations where ref_no LIKE '%q%')")
->asArray()->all();

OR

$ser = Survey::find()
->where("ref_no like '%$q%' AND ref_no NOT IN (select ref_no from installations where ref_no LIKE '%q%')")
->andWhere(['status'=>1])
->asArray()->all();
Yasin Patel
  • 5,624
  • 8
  • 31
  • 53