尝试按照多种关系计算结果

时间:2015-02-21 16:41:27

标签: symfony doctrine-orm many-to-many

当我尝试对多对多关系进行计数并在按顺序对结果进行排序时,我遇到了问题。

这是我的关系实体:

/**
 * @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;

这是我的Repository方法:

/**
 * 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.

你能帮助我吗?

2 个答案:

答案 0 :(得分:0)

可能 :按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));

答案 1 :(得分:0)

谢谢大家。

它有效,这是我的解决方案

    $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才能获得所有引号。