How to create a `IN` clause in CakePHP query?
Asked Answered
F

4

11

How do you make it where in clause in new CakePHP? I'm trying:

$restaurants->find()->where(['id' => $r_ids])->all();

Where $r_ids is array of ids I need in my query, but this doesn't work as expected.

Filagree answered 12/11, 2014 at 12:54 Comment(0)
L
35

With CakePHP 3.x it's now necessary to either indicate the data type, which for an array of values need to have [] appended to the type:

$query = $articles
    ->find()
    ->where(['id' => $ids], ['id' => 'integer[]']);

or to explicitly make use of the IN keyword:

$query = $articles
    ->find()
    ->where(['id IN' => $ids]);

See also

Lariat answered 12/11, 2014 at 13:5 Comment(3)
If we have to check multiple columns in IN clause then how to do? What to do in this case : ->where(['id,name IN' => ??]);Vanadous
@Vanadous You'll have to use the tuple comparison expression: https://mcmap.net/q/671494/-query-builder-in-clause-with-composite-columnsLariat
tysm. This is what i was looking for.Vanadous
L
1

Try this one for CakePHP 3.x

$query = $restaurants
    ->find()
    ->where(['id IN' => $r_ids]);
$query->all();
Lowboy answered 21/3, 2017 at 4:43 Comment(0)
C
0

You can also use the short syntax:

    $result = $restaurants->find('all', 
            ['conditions' => ['id IN' =>$r_ids]]
        )->all();
Crank answered 4/2, 2018 at 14:23 Comment(0)
S
0

In Cakephp 3.x, If you have multiple where conditions then your query will be as below:

return $this
        ->find()
        ->contain([
            'XYZ.Articles',
            'YYY.Managers',
            'ZZZ.Readers',
        ])
        ->where([
            'ID' => $ids,
            'READER.STATUS' => $xyz,
        ],[
            'ID' => 'integer[]'
        ])
        ;
Scarborough answered 6/12, 2018 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.