在Doctrine2查询构建器中链接orX

时间:2012-03-22 00:57:50

标签: mysql sql doctrine doctrine-orm

我必须在添加OR子句后立即将getListQueryBuilder表达式动态添加到where返回的查询构建器中。我找不到任何合适的方法,我刚开始学习Doctrine。

如何“链接”给定数量的orX并将其添加到我的构建器中?

public function getListQueryBuilder($ownerId)
{
    $qb = $this->createQueryBuilder('t');

    return $qb
        ->where($qb->expr()->eq('t.user', ':user'))
        ->setParameter('user', $ownerId);
}

$builder = getListQueryBuilder(4);

// $ORs is a dynamically builded array, here is just an example
$ORs = array();
$ORs[] = $builder->expr()->like("t.name", 'my name');
$ORs[] = $builder->expr()->like("t.description", 'desc');

// Adding ORs to the builder
$builder->andWhere($builder->expr()->orX(/* here */));

2 个答案:

答案 0 :(得分:22)

您可以查看this solution

$orX = $builder->expr()->orX();
foreach($ORs as $or) {
    $orX->add($or);
}
$builder->andWhere($orX);

答案 1 :(得分:8)

我偶然发现了同样的问题并尝试过:

$builder->andWhere($builder->expr()->orX($ORs));

但由于orX调用“返回new Expr \ Orx(func_get_args());”它不起作用;“在内部,你最终得到像array(array(or1,or2))

之类的东西

查看了API,但我认为你可以这样做:

$builder->andWhere($builder->expr()->orX()->addMultiple($ORs));

或者使用$ ORs表,但问题是:

$orx = $builder->expr()->orX();
$orx->add($builder->expr()->like("t.name", 'my name'));
$orx->add($builder->expr()->like("t.description", 'desc'));
$builder->andWhere($orx);