【问题标题】:how to get the most used tags with Doctrine?如何使用 Doctrine 获取最常用的标签?
【发布时间】:2015-04-29 13:46:34
【问题描述】:

我有两个实体,“Pin”和“Tag”,具有多对多关系。 我想获取最常用的标签顺序列表,以显示在表单中

这里是我的存储库的方法:

    public function findPopularTag(){
    return $qb = $this->createQueryBuilder('t')
    ->addSelect('COUNT(DISTINCT  p.id) AS total_pins')
    ->leftJoin('t.listeEpingles', 'p')
    ->groupBy('t.id')
    ->orderBy('total_pins','DESC');


}

在我的 buildForm 中,我使用这个方法来创建一个 entityType:

            $builder->add(  'listeTagsDansListeEpingles', 'entity', array(
                'class'    => 'SharincookRecipesBundle:Tag',
                'required'  =>false,
                'multiple' => true,
                'property' => 'libelle',
                'expanded'=>true,
                'query_builder' => function(TagRepository $repo){
                    return $repo->findPopularTag();
                },


        ));

但我有一个错误: 给定类型“对象或数组”、“字符串”的预期参数vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php 第 224 行

【问题讨论】:

  • 您在orderBy() 之后添加了->getQuery()->getResult() 吗?在您的示例代码中,这是缺少的
  • 我不能这样做,因为我必须在我的 buildForm 中获得一个 queryBuilder。
  • 试试这个`->addSelect('COUNT(DISTINCT p.id) AS HIDDEN total_pins')`,这样ORM就不会在结果集中获取该列的结果
  • 非常感谢!!!!!!有用!!!自从五天以来我一直在处理这个问题
  • 很高兴能为你 +1 帮助

标签: symfony doctrine query-builder


【解决方案1】:

您可以在查询构建器中使用左连接和排序

$tag = $em->getRepository('NamespaceYourBundle:Tag');
$qb = $tag->createQueryBuilder('t')
        ->addSelect('COUNT(DISTINCT  p.id) AS HIDDEN total_pins')
        ->leftJoin('t.pins', 'p');
        ->groupBy('t.id')
        ->orderBy('total_pins','DESC')
        ->getQuery()
        ->getResult();

【讨论】:

  • 感谢您的回答,但它返回一个 Pin 列表,我只想要一个标签列表。因为我在实体类型的构建表单中调用该方法
  • @sepointes 抱歉,我错误地发布了答案,请参阅我的更新答案
  • 我将您的代码放在我的存储库中:public function findPopularTag(){ return $qb = $this->createQueryBuilder('t') ->addSelect('COUNT(DISTINCT p.id) AS total_pins') ->leftJoin('t.listeEpingles', 'p') ->groupBy('t.id') ->orderBy('total_pins','DESC'); } 并在我的 entityType 中调用此方法,但我有一个错误:“对象或数组”、“字符串”类型的预期参数给定
  • @sepointes 如果您使用错误代码中所需的代码更新您的问题,它会更好,似乎错误与查询以外的其他问题有关
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-16
  • 2016-07-11
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
相关资源
最近更新 更多