Search code examples
doctrine-ormdqlwhere-in

Is this the proper way to handle an ordered array with Doctrine2's WHERE IN expression?


Using Zend Lucene Search, I am returning a list of relevance-ordered IDs that map to blog records that I will fetch from the database.

Is this the proper way of handling an array with Doctrine2's WHERE IN expression:

$dql = "SELECT b FROM BlogPost WHERE b.id IN (" . implode(', ', $ids) . ")";
$query = $em->createQuery($dql);
...

Or is there a better way of maybe passing in the actual $ids array as a parameter to the query?

Also, the Zend Search returns the array of IDs based on relevance. Will using the above technique preserve the order of relevance in retrieving the blog posts?


Solution

  • If it makes you feel better, you can use the ExpressionBuilder.

    $ex = $em->getExpressionBuilder();
    $dql = 'SELECT b FROM BlogPost b WHERE ' . $ex->in('b.id', $ids));
    $query = $em->createQuery($dql);
    
    function cmp($a, $b) {
        global $ids;
        return (array_search($a->getId(), $ids) < array_search($b->getId(), $ids)) ? -1 : 1;
    }
    usort($res, 'cmp');
    

    It's a bit cleaner, but does the same as you behind the screens.