Search code examples
phalconphalcon-orm

Is it possible to run findFirst() with IN clause in Phalcon?


I would like to use an IN clause in findFirst but it doesn't seem to work?

Expected code, or something similar:

$item = Item::findFirst([
    'conditions' => 'categories IN :cats: AND released < :now:',
    'order'      => 'id ASC',
    'bind'       => [
        'cats'     => $this->categories,
        'released' => time()
    ],
]);

I tried using bindTypes but there's no such "list" or "array" type (also, that would get a lot more verbose than expected)...

I know I can do it through the query builder, but I was looking to keep it a bit more idiomatic:

$item = Item::query()
    ->inWhere('categories', $this->categories)
    ->andWhere('released < :now:', ['now' => time()])
    ->orderBy('id ASC')
    ->limit(1)
    ->execute()
    ->getFirst();

Solution

  • You can bind the array and IN clause like this:

    $result = ModelName::findFirst([
        'conditions' => 'id in ({cats:array})',
        'bind' => array('cats' => [3, 5, 8])
    ]);
    

    Note that the above example will get the first record with id 3. However if you use find() you will get the items with 3, 5 and 8.

    More examples in the docs (at the bottom of this section).