【问题标题】:Symfony2/Doctrine QueryBuilder using andwhere()Symfony2/Doctrine QueryBuilder 使用 andwhere()
【发布时间】:2012-01-16 01:42:14
【问题描述】:

我在存储库类中使用以下方法在我的数据库中查找某些标签:

public function getItemsByTag($tag, $limit = null)
{
    $tag = '%'.$tag.'%';

    $qb = $this->createQueryBuilder('c');

    $qb->select('c')
       ->where($qb->expr()->like('c.tags', '?1'))
       ->setParameter(1, $tag)
       ->addOrderBy('c.clicks', 'DESC');

    if (false === is_null($limit))
        $qb->setMaxResults($limit);

    return $qb->getQuery()->getResult();
}

这很好用。但是:如何添加 2 个附加变量(其中:已审核 = 1,启用 = 1)?我试过 andwhere() 但我无法弄清楚。

我还发现是这样的:

public function getItems($limit = null)
{
        $qb = $this->createQueryBuilder('b')
               ->select('b')
               ->add('where', 'b.reviewed = 1')
               ->add('where', 'b.enabled = 1')
               ->addOrderBy('b.name', 'ASC');

        // ...
}

也不行……

有什么提示吗?

【问题讨论】:

    标签: doctrine symfony


    【解决方案1】:

    我会这样写:

    $qb = $this
        ->createQueryBuilder('c')
        ->where('c.tags LIKE :tag')
        ->andWhere('c.reviewed = 1')
        ->andWhere('c.enabled = 1')
        ->setParameter('tag', "%{$tag}%")
        ->orderBy('c.clicks', 'DESC')
        ->addOrderBy('b.name', 'ASC');
    
    if ($limit) {
        $qb->setMaxResults($limit);
    }
    
    return $qb->getQuery()->getResult();
    

    你也可以联合那些where条件:

    ->where('c.tags LIKE :tag AND c.reviewed = 1 AND c.enabled = 1')
    

    【讨论】:

    • 我相信使用 addOrderBy 是您将逻辑连接到 orderBy。例如,如果您想要 2 个 orderBy 参数,第一个是“orderBy”,然后是“addOrderBy”。与 where 子句的工作方式相同。第一个是->where,然后后面的都写成'->addWhere'。
    • 谢谢,节省了我一些时间。
    【解决方案2】:

    来自manual,建议的方式如下:

    $qb->select(array('c'))
       ->where($qb->expr()->orx(
           $qb->expr()->eq('c.reviewed', 1),
           $qb->expr()->eq('c.enabled', 1),
           $qb->expr()->like('c.tags', '?1')
       ))
       ->orderBy('c.clicks', 'DESC'));
    

    【讨论】:

    • 好的,谢谢 xdazz +1!
    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-17
    相关资源
    最近更新 更多