80

我有这个 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 选择不同的?

4

4 回答 4

181

这有效:

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

于 2013-10-22T16:32:39.050 回答
55

如果你使用“select()”语句,你可以这样做:

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

$categories = $category->getResult();
于 2012-01-25T10:04:41.607 回答
30

你可以写

select DISTINCT f from t;

作为

select f from t group by f;

问题是,我自己现在才刚刚进入 Doctrine,所以我不能给你一个真正的答案。但是您可以如上所示,用group by模拟一个 distinct并将其转换为Doctrine。如果要添加进一步过滤,请HAVING在 group by 之后使用。

于 2011-08-25T13:28:03.637 回答
-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
    ]);
}

祝你好运!

于 2019-12-20T16:00:18.300 回答