doctrine - Symfony2/Doctrine QueryBuilder 使用 andwhere()

标签 doctrine symfony

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

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 个附加变量(其中:reviewed = 1,enabled = 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');

        // ...
}

也行不通...

有什么提示吗?

最佳答案

我会这样写:

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

关于doctrine - Symfony2/Doctrine QueryBuilder 使用 andwhere(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874987/

相关文章:

symfony - 文档 :mapping:import for Symfony2 中未知的数据库类型几何请求错误

postgresql - 主键上带有 PostgreSQL 序列的 Doctrine 更新模式

symfony - 奏鸣曲sonata_type_collection显示表

javascript - 为 Datetimepicker Bundle 设置回调

php - 如何使UploadedFile对UnitTest无效?

Doctrine :通过拥有来分组

php - 对于 Doctrine,使用 DQL 而不是 SQL 有什么好处?

php - 3 个表之间的 Symfony Doctrine 关系

php - 学说多对多关联 prePersist 数据复制

doctrine - 查询生成器/DQL无法与INNER JOIN一起使用-语法问题