7

The following active record WHERE IN query does not work. According to the docs this should work:

$data = $dropDownData->find()
                    ->select('country, country_text')
                    ->distinct()
                    ->WHERE(['in', 'server', $servers]);

$listData = ArrayHelper::map($data,'country', 'country_text');

The sql equivalent is :

$query = "SELECT DISTINCT country, country_text 
          FROM `dropDownData` 
          WHERE server IN ({$servers})";

$servers just contains a string 1,2,4

What am I doing wrong here?

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
user794846
  • 1,881
  • 5
  • 29
  • 72

2 Answers2

14

Based on Yii2 documentation $servers should be an array not a string.

in: operand 1 should be a column or DB expression. Operand 2 can be either an array or a Query object.

https://www.yiiframework.com/doc/guide/2.0/en/db-query-builder#operator-format

Try using a proper array:

  $servers = [1,2,4]
  $data = $dropDownData->find()
                      ->select('country, country_text')
                      ->distinct()
                      ->WHERE(['in', 'server',[1,2,4]]);

or

  $data = $dropDownData->find()
                      ->select('country, country_text')
                      ->distinct()
                      ->WHERE(['in', 'server', $servers]);
rob006
  • 21,383
  • 5
  • 53
  • 74
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
-1

You should use array variable

$servers = [1,2,4];