Is this the right way to handle an ordered array with a Doctrine2 WHERE IN expression?

Using Zend Lucene Search, I return a list of identifiers sorted by relevance that are mapped to blog entries that I will retrieve from the database.

This is the correct way to handle an array with a Doctrine2 WHERE IN expression:

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

Or is there a better way, perhaps passing $ids in the actual array as a parameter to the request?

In addition, Zend Search returns an array of identifiers based on relevancy. Will using the above method maintain relevance when receiving blog posts?

+4
source share
2 answers

If you feel better, you can use 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 is a little cleaner, but it does the same as you behind the screens.

+4
source

You must represent the $ ids array using the setParameter () function, as this is the best practice in the doctrine:

 $query = $this->_em->createQuery('SELECT b FROM BlogPost WHERE b.id IN (?1)'); $query->setParameter(1, implode(',', $ids)); 

I think that the IN instruction will not preserve the order of the transmitted ID, since IN will match the first found $ id, independent of the order.

+1
source

Source: https://habr.com/ru/post/1345247/


All Articles