【问题标题】:Symfony2 index of an object sorted by DQLSymfony2 按 DQL 排序的对象的索引
【发布时间】:2016-01-31 18:05:18
【问题描述】:

您好,我已经使用查询生成器对排名机制进行了简单查询。

        $result = $qb
            ->select('u')
            ->where('u.status = 1')
            ->from('PGMainBundle:User', 'u')
            ->groupBy('u.id')
            ->addSelect('COUNT(c.id) as HIDDEN nChallenges')
            ->leftJoin('u.challenges', 'c', 'WITH', 'c.closed = 1' )
            ->add('orderBy','u.points DESC, nChallenges DESC')
            ->orderBy('u.points', 'DESC')
            ->addOrderBy('nChallenges', 'DESC')
            ->setFirstResult($offset*50)
            ->setMaxResults(50)
            ->getQuery()
            ->getResult();

现在,虽然我的排名机制运行良好,但我想检查一个具有 $id 的用户有什么 loop.index。

这么说,我不想在结果上使用 foreach 循环来这样做。

是否有更优化的方式来返回排名中的“位置”?

可能使用查询生成器?

【问题讨论】:

    标签: php symfony query-builder doctrine-query


    【解决方案1】:

    结果应该是array collection,因此您可以像这样获取给定元素的索引:

    $result->indexOf($yourelement)
    

    否则,如果键不按顺序排列,而是实体的 id:

      $keys = $result->getKeys();
      $id = $yourElement->getId();
      $position = array_search($id, $keys);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-09-21
      • 2014-10-31
      • 1970-01-01
      相关资源
      最近更新 更多