如何使用symfony2 doctrine查询构建器选择不同的查询?

时间:2011-08-25 09:45:11

标签: 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();

但是会导致以下错误:

  

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

如何告诉symfony选择distinct?

4 个答案:

答案 0 :(得分:158)

这有效:

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

$categories = $category->getResult();

答案 1 :(得分:49)

如果使用“select()”语句,则可以执行以下操作:

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

$categories = $category->getResult();

答案 2 :(得分:27)

你可以写

select DISTINCT f from t;

作为

select f from t group by f;

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

答案 3 :(得分:-1)

只需打开您的存储库文件并添加此新函数,然后在您的控制器中调用它即可:

 public function distinctCategories(){
        return $this->createQueryBuilder('cc')
        ->where('cc.contenttype = :type')
        ->setParameter('type', 'blogarticle')
        ->groupBy('cc.blogarticle')
        ->getQuery()
        ->getResult()
        ;
    }

然后在您的控制器内:

public function index(YourRepository $repo)
{
    $distinctCategories = $repo->distinctCategories();


    return $this->render('your_twig_file.html.twig', [
        'distinctCategories' => $distinctCategories
    ]);
}

祝你好运!

相关问题