我想在查询构建器中添加orWhere条件。 params将来自阵列。但我不知道如何添加等于计数数组元素的orWhere语句的数量。这是一些代码:
public function selectRelatedTrips($assoc)
{
$params = array('k' => 'Kiev');
$query = $this
->getEntityManager()
->createQueryBuilder()
->select('t')
->from('VputiTripBundle:Trip', 't')
->where('t.startCity = :k');
foreach ($assoc as $k => $v) {
// $query->orWhere('t.startCity = ' . $v);
$query->where('t.startCity = :param' . $k);
$params['param' . $k] = $v;
}
return $query->setParameters($params)
->setMaxResults(20)
->orderBy('t.id', 'desc')
->getQuery()
->getResult();
}
有人可以帮帮我吗?
答案 0 :(得分:2)
您可以使用in()
功能:
class AcmeRepository extends EntityRepository
{
public function selectRelatedTrips($assoc)
{
$qb = $this->createQueryBuilder('e');
$qb = $qb
->where(
$qb->expr()->in('e.field2', array_keys($assoc))
);
return($qb->getQuery()->getResult());
}
}
请参阅How to use WHERE IN with Doctrine 2和Doctrine2 Query Builder以获取参考资料。
答案 1 :(得分:1)
尝试根据您的数组动态构建查询:
$params = array('param1' => 123);
$query = $this
->createQueryBuilder('e')
->select('e')
->where('e.field = :param1')
foreach ($assoc as $k => $v) {
$query->orWhere('e.field2 = :param'.$k);
$params['param'.$k] = $v;
}
$query->setParameters($params);