如何使用 symfony2 学说查询构建器选择不同的查询? [英] How to select distinct query using symfony2 doctrine query builder?
问题描述
我有这个 symfony 代码,它检索与我的项目中的博客部分相关的所有类别:
I have this symfony code where it retrieves all the categories related to a blog section on my project:
$category = $catrep->createQueryBuilder('cc')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
这有效,但查询包含重复项:
This works, but the query includes duplicates:
Test Content
Business
Test Content
我想在查询中使用 DISTINCT
命令.我见过的唯一示例要求我编写原始 SQL.我想尽可能避免这种情况,因为我试图保持所有代码相同,以便它们都使用 Symfony2/Doctrine 提供的 QueryBuilder 功能.
I want to use the DISTINCT
command in my query. The only examples I have seen require me to write raw SQL. I want to avoid this as much as possible as I am trying to keep all of my code the same so they all use the QueryBuilder feature supplied by Symfony2/Doctrine.
我尝试将 distinct()
添加到我的查询中,如下所示:
I tried adding distinct()
to my query like this:
$category = $catrep->createQueryBuilder('cc')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->distinct('cc.categoryid')
->getQuery();
$categories = $category->getResult();
但它导致以下错误:
致命错误:调用未定义的方法 DoctrineORMQueryBuilder::distinct()
Fatal error: Call to undefined method DoctrineORMQueryBuilder::distinct()
我如何告诉 symfony 选择不同的?
How do I tell symfony to select distinct?
推荐答案
你可以写
select DISTINCT f from t;
作为
select f from t group by f;
问题是,我目前刚刚进入 Doctrine,所以我不能给你一个真正的答案.但你可以如上所示,用 group by 并将其转换为 学说.如果你想添加进一步的过滤,那么在 group by 之后使用 HAVING
.
thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING
after group by.
这篇关于如何使用 symfony2 学说查询构建器选择不同的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!