如何使用symfony2 doctrine查询构建器选择不同的查询? [英] How to select distinct query using symfony2 doctrine query builder?

查看:170
本文介绍了如何使用symfony2 doctrine查询构建器选择不同的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$ categories = $ category-> getResult();

这样做有效,但查询包含重复项:

 测试内容
商业
测试内容

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



我尝试向我的查询添加 distinct()

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

$ categories = $ category-> getResult();

但是会导致以下错误:



< blockquote>

致命错误:调用未定义的方法Doctrine\ORM\QueryBuilder :: distinct()


如何告诉symfony选择不同的?

解决方案

你可以写

 从t选择DISTINCT f; 

as

 从f组中选择f f; 

事情是,我只是目前正在进入Doctrine,所以我不能给你一个真正的答案。但是,如上所示,您可以使用 group by 并将其转换为 Doctrine 。如果你想添加进一步的过滤,然后使用 HAVING 在组之后。


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

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.

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

But it results in the following error:

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

How do I tell symfony to select distinct?

解决方案

you could write

select DISTINCT f from t;

as

select f from t group by f;

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 doctrine查询构建器选择不同的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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