尝试使用对多对多关系的计数对结果进行排序

Try to sort a result with a count on a manytomany relation

当我尝试对多对多关系进行计数并按它对结果进行排序后,我遇到了一个问题。

这是我的关系实体:

/**
 * @ORM\ManyToMany(targetEntity="QuoteBox\Bundle\UserBundle\Entity\User", inversedBy="likedQuotes")
 * @ORM\JoinTable(
 *     name="JNT_liker",
 *     joinColumns={
 *         @ORM\JoinColumn(
 *             name="QUOTE_id",
 *             referencedColumnName="QUOTE_id",
 *             nullable=false
 *         )
 *     },
 *     inverseJoinColumns={@ORM\JoinColumn(name="USER_id", referencedColumnName="USER_id", nullable=false)}
 * )
 */
private $likers;

这是我的存储库方法:

/**
 * Find All by number of Likes Adapter
 * @return Pagerfanta
 */
public function findAllByLikesAdapter(Location $location)
{
    $query = $this->getCommonQuery($location);
    $query->select('q, count(q.likers) as HIDDEN num_like');
    $query->innerJoin('q.likers', 'likers');
    $query->groupBy('q.id');
    $query->orderBy('num_like', 'ASC');
    return new Pagerfanta(new DoctrineORMAdapter($query));
}

这是我的控制器:

    public function topAction(Location $location, $page = 1)
    {
    $pager = $this->getDoctrine()->getRepository("QuoteBoxQuoteBundle:Quote")->findAllByLikesAdapter($location);
    $pager->setMaxPerPage(5);
    $pager->setCurrentPage($page);
    return [ 'pager' => $pager, 'location' => $location ];
    }

这是我使用 twig 和 pagerfanta 的观点:

{% for quote in pager.currentPageResults %}
    {% include "QuoteBoxQuoteBundle:line:quote.html.twig" with {'quote':quote, 'currentPage':pager.currentPage } only %}
{% endfor %}

当我在这里执行它时出现错误:

> An exception has been thrown during the rendering of a template ("[Semantical Error] line 0, col 18 near 'likers) as HIDDEN': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.") in QuoteBoxQuoteBundle:Quotes:quotes.html.twig at line 13.

你能帮帮我吗?

可能 : 将 q.likers 更改为 likers

$query = $this->getCommonQuery($location);
$query->select('q, count(likers) as HIDDEN num_like');  // <-- HERE
$query->innerJoin('q.likers', 'likers');    // Because you called it 'likers' here
$query->groupBy('q.id');
$query->orderBy('num_like', 'ASC');
return new Pagerfanta(new DoctrineORMAdapter($query));

谢谢大家。

有效,这是我的解决方案

    $query = $this->getCommonQuery($location);
    $query->addSelect('q, COUNT(likers.id) AS HIDDEN num_likers');
    $query->leftJoin('q.likers', 'likers');
    $query->groupBy('q.id');
    $query->orderBy('num_likers', 'DESC');

我必须添加 leftJoin 而不是 join 才能获得我的所有报价。