php - 如何使用 symfony2 学说查询生成器选择不同的查询?

标签 php doctrine-orm symfony query-builder

我有这个 symfony 代码,它可以检索与我项目中的博客部分相关的所有类别:

$category = $catrep->createQueryBuilder('cc')
    ->Where('cc.contenttype = :type')
    ->setParameter('type', 'blogarticle')
    ->getQuery();

$categories = $category->getResult();

这可行,但查询包含重复项:

Test Content
Business
Test Content

我想在我的查询中使用 DISTINCT 命令。我见过的唯一示例要求我编写原始 SQL。我想尽可能避免这种情况,因为我试图保持所有代码相同,以便它们都使用 Symfony2/Doctrine 提供的 QueryBuilder 功能。

我尝试将 distinct() 添加到我的查询中,如下所示:

$category = $catrep->createQueryBuilder('cc')
    ->Where('cc.contenttype = :type')
    ->setParameter('type', 'blogarticle')
    ->distinct('cc.categoryid')
    ->getQuery();

$categories = $category->getResult();

但是会导致如下错误:

Fatal error: Call to undefined method Doctrine\ORM\QueryBuilder::distinct()

我如何告诉 symfony 选择 distinct?

最佳答案

这行得通:

$category = $catrep->createQueryBuilder('cc')
        ->select('cc.categoryid')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->distinct()
        ->getQuery();

$categories = $category->getResult();

为 Symfony 3 和 4 编辑。

你应该使用 ->groupBy('cc.categoryid') 而不是 ->distinct()

关于php - 如何使用 symfony2 学说查询生成器选择不同的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7188219/

相关文章:

symfony - include标签和include函数有什么区别?

php - 获取 Uncaught ReferenceError : using PHP

symfony - 有没有办法告诉 Doctrine 不要碰特定的 table ?

php - Doctrine 模型数组数据类型

php - 操作方法 : Optimize Symfony's forms' performance?

mysql - Symfony - 选择日期 = 今天的对象

php - 是否可以在 php 5.2.6 中使用 SplEnum?

php - Yii 中 findBySQL 的结果

php - 重新发送电子邮件的功能将我带到主页,并且在给定功能中什么都不做 - Laravel

symfony - 使用 FOSRestBundle 和 Symfony2 覆盖路由中的默认值 ".{_format}"