Kuldeep Dangi
Kuldeep Dangi

Reputation: 4422

In yii2 query builder how to use in operator with where clause

I did not find any example of yii2 query builder yii\db\Query using in operator with where clause. for the time being I am using it this way

$result = (new \yii\db\Query)
    ->select('*')
    ->from('customer c')
    ->where('c.status in (' . implode(',', [0,1]) . ')')->all();

But there must be a better way of doing this. Thanks in advance

Upvotes: 3

Views: 8411

Answers (1)

drodata
drodata

Reputation: 527

$result = (new \yii\db\Query)
    ->select('*')
    ->from('customer c')
    ->where(['c.status' => [0, 1]])->all();

In the yii\db\QueryInterface::where() API:

The $condition specified as an array can be in one of the following two formats:

  • hash format: ['column1' => value1, 'column2' => value2, ...]
  • operator format: [operator, operand1, operand2, ...]

... In case when a value is an array, an IN expression will be generated.

  • ['id' => [1, 2, 3], 'status' => 2] generates (id IN (1, 2, 3)) AND (status = 2).

Upvotes: 10

Related Questions