Symfony2/Doctrine QueryBuilder 使用 andwhere() [英] Symfony2/Doctrine QueryBuilder using andwhere()

查看:20
本文介绍了Symfony2/Doctrine QueryBuilder 使用 andwhere()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using following method in a repository class to look for certain tags in my database:

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() 但我无法弄清楚.

This works just nice.. But: How can I add 2 additional variables (where: reviewed = 1, enabled = 1)? I tried andwhere() but I couldn't figure it out.

我还发现是这样的:

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');

        // ...
}

也不行……

有什么提示吗?

推荐答案

我会这样写:

$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 条件:

You could also unite those where conditions:

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

这篇关于Symfony2/Doctrine QueryBuilder 使用 andwhere()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆