How to use andWhere and orWhere in Doctrine?

WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2)

How can i make this in Doctrine?

$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")

this isnt correctly... Should be:

$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")

but how can i make it? In Propel is function getNewCriterion, and in Doctrine...?

133510 次浏览
$q->where("a = 1")
->andWhere("b = 1 OR b = 2")
->andWhere("c = 2 OR c = 2")
;

为什么不呢

$q->where("a = 1");
$q->andWhere("b = 1 OR b = 2");
$q->andWhere("c = 1 OR d = 2");

编辑 : 您也可以使用 专业级(Doctrine2)。

这里有一个例子,对于那些有更复杂的条件和使用原则2。 * 与 QueryBuilder:

$qb->where('o.foo = 1')
->andWhere($qb->expr()->orX(
$qb->expr()->eq('o.bar', 1),
$qb->expr()->eq('o.bar', 2)
))
;

这些都是捷克答案中提到的表达方式。

这里缺少一样东西: 如果你有不同数量的元素,你想把它们放在一起

WHERE [...] AND (field LIKE '%abc%' OR field LIKE '%def%')

如果你不想自己组装一个 DQL-String,你可以像这样使用上面提到的 orX:

$patterns = ['abc', 'def'];
$orStatements = $qb->expr()->orX();
foreach ($patterns as $pattern) {
$orStatements->add(
$qb->expr()->like('field', $qb->expr()->literal('%' . $pattern . '%'))
);
}
$qb->andWhere($orStatements);