4

使用 Zend Lucene Search,我返回了一个相关性排序的 ID 列表,这些 ID 映射到我将从数据库中获取的博客记录。

这是使用 Doctrine2 的 WHERE IN 表达式处理数组的正确方法吗:

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

或者有没有更好的方法可以将实际$ids数组作为参数传递给查询?

此外,Zend Search 根据相关性返回 ID 数组。使用上述技术会保留检索博客文章的相关顺序吗?

4

2 回答 2

4

如果它让您感觉更好,您可以使用 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');

它有点清洁,但与屏幕后面的你一样。

于 2011-04-15T09:15:45.990 回答
1

You should pas the $ids array through setParameter() function as this is a best practice in doctrine:

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

I think the IN statement will not preserve the order of the passed ID's as IN will match the first found $id not depending on the order.

于 2011-04-14T09:20:08.380 回答