Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 WHERE IN query

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?

like image 600
user794846 Avatar asked Jul 09 '18 16:07

user794846


People also ask

How to write query in yii?

use createcommand() method: use yii\db\Query(); $connection = \Yii::$app->db; $query = new Query; $insql = $connection->createCommand("SELECT* FROM inventory ); $result=$insql->queryAll(); the above method list all data from the inventory table.

Is null in Yii2 query?

Yii2 will use "IS NULL" if the $values === null , but in case the value is supplied as an array, and one of those array elements is null, it will not get any special treatment, resulting in the query never matching any records with NULL value.

What is query Builder in php?

It can be used to perform most database operations in your application, and works on all supported database systems. Note: The Laravel query builder uses PDO parameter binding throughout to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.


1 Answers

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]);
like image 84
ScaisEdge Avatar answered Sep 16 '22 15:09

ScaisEdge