这是dql-query
$dql = "SELECT t Entities\Table t WHERE t.field IN (?1)";
$q = $em->createQuery($dql)
->setParameter(1, '108919,108920');
$result = $q->execute();
如果我通过setParameter传递参数doctrine只返回第一个结果,但是如果我将它们直接放入dql-query中则返回2个结果(这是正确的):
$dql = "SELECT t Entities\Table t WHERE t.field1 IN (108919,108920)";
如何通过setParameter处理WHERE子句中的“IN”?
答案 0 :(得分:9)
请注意,这仅适用于编号参数,而不适用于命名参数。
$searchParameters = array(108919, 108920);
$dql = "SELECT t Entities\Table t WHERE t.field IN (?1)";
$q = $em->createQuery($dql)
->setParameter(1, $searchParameters);
$result = $q->execute();
答案 1 :(得分:6)
以下应该可以正常工作:
$searchParameters = array(108919, 108920);
$dql = "SELECT t Entities\Table t WHERE t.field IN (?1)";
$q = $em->createQuery($dql)
->setParameter(1, $searchParameters);
$result = $q->execute();
你可以传入一个数组,而不使用implode(),而且doctrine会正确处理它(作为整数列表)。
注意:如果您已使用字符串'108919,108920',则需要使用explode和trim函数。
这里也提到了这一点:How to use the in statement in DQL in Doctrine 2.0
答案 2 :(得分:1)
以下内容应按预期工作(对于IN
子句的任意数量的参数)
$params = array(1 => 108919, 2 => 108920);
$qb = $em->createQueryBuilder();
$qb->select(array('t'))
->from('Entities\Table', 't')
->where($qb->expr()-> in('t.field', array_map(function($p) { return '?'.$p; }, array_keys($params)))
->setParameters($params);
$q = $qb->getQuery();
$r = $q->getResult();
答案 3 :(得分:0)
解决方案1:
$dql = "SELECT t Entities\Table t WHERE t.field IN (?1, ?2)";
$q = $em->createQuery($dql)
->setParameters(array(1 =>'108919', 2 => '108920'));
$result = $q->execute();
解决方案2(更优雅):
$parameters = array(1 =>'108919', 2 => '108920');
$dql = 'SELECT t Entities\Table t WHERE t.field IN (?'.implode(', ?', array_keys($parameters)).')';
$q = $em->createQuery($dql)
->setParameters($parameters);
$result = $q->execute();
答案 4 :(得分:0)
这是有效的
public function searchCategory($target){
$query = $this->getEntityManager()
->createQuery("SELECT ct.id as id,ct.name as name, ct.target as target FROM LoveThatFitAdminBundle:ClothingType ct WHERE ct.target IN (:target)")
->setParameter('target',$target['target']);
try {
return $query->getResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
}