beginner
beginner

Reputation: 45

Yii2 select query where multiple values

When I want select where IN query, how to define multiple values in where clause?

Note on the ':k'=>1 and ':k'=>, how to use it for 2 values?

$query = Model::find()->where('id = :id and type = :k' ,[':id'=>$id, ':k'=>1,':k'=>27])->count();

Upvotes: 2

Views: 2094

Answers (3)

rob006
rob006

Reputation: 22174

Conditions can be also defined using array syntax:

$count = Model::find()
    ->where([
        'AND',
        ['=', 'id', $id],
        ['IN', 'type', [1, 27]],
    ])
    ->count();

Upvotes: 2

rakhmatov
rakhmatov

Reputation: 377

You can do it in this way:

$types = [1, 27];
$query = Model::find()
    ->where(['id' => $id])
    ->andWhere(['type' => $types])
    ->count();

Yii2 will convert your $types array to IN condition. SQL query will be:

SELECT COUNT(*) FROM <table> WHERE id = <id> AND type IN (1, 27);

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133400

You could try using IN baded on an array assuming

$myArray = array(1,27);
$query = Model::find()->where(['IN', 'id', $myArray])
    ->andWhere('id = :id', [':id' => $id])->count();

Upvotes: 1

Related Questions