我有这个 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/