Symfony主义SortBy ToMany关系对象

时间:2019-02-01 20:12:39

标签: symfony doctrine

我有实体文章和要点,它们由oneToMany关系连接。我想要make方法,该方法将返回具有最多相关注释数的对象。 可能吗? 请帮助,我没有任何想法。

https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/ordered-associations.html-我应该使用它吗?

实体: 帖子:

/**
 * @ORM\Entity(repositoryClass="App\Repository\PostRepository")
 */
class Post
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var Points
     * @ORM\OneToMany(targetEntity="Points", mappedBy="post", fetch="EAGER")
     */
    private $points;

    /**
     * @return Collection|Points[]
     */
    public function getPoints(): Collection {
        return $this->points;
    }

...

/**
 * @ORM\Entity(repositoryClass="App\Repository\PointsRepository")
 */
class Points
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var Post
     * @ORM\ManyToOne(targetEntity="Post", inversedBy="points",  fetch="EAGER")
     */
    private $post;

    public function getPost(): Post {
        return $this->post;
    }

    public function setPost(Post $post ){
        $this->post = $post;
    }
...

2 个答案:

答案 0 :(得分:1)

假设您已经可以返回带有其要点的帖子,则可以尝试如下操作:

在App \ Repository \ PostRepository中:

public function postsByPoints() {
    return $this->getEntityManager()->createQueryBuilder()
        ->select('p.post, count(pt.points) N)
        ->from('App:Points', 'pt')
        ->join('pt.post', 'p')
        ->where('some where clause') <- delete this if you're not selecting a subset
        ->groupBy('p.post')
        ->orderBy('N')
        ->getQuery()->getResult();
}

在某些控制器中:

$em = $this->getDoctrine()->getManager();
$postsByPoints = $em->getRepository('App:Post')->postsByPoints();

NB:未经测试

答案 1 :(得分:0)

这是一个工作(我)代码

        return $this->createQueryBuilder('p')
            ->innerJoin('p.user', 'c')
            ->innerJoin('p.points', 'pp')
            ->andWhere("p.date > '".$now->format("Y-m-d H:i:s")."'")
            ->setMaxResults($max)
            ->groupBy('pp.post')
            ->orderBy('pp.post','DESC')
            ->getQuery()
            ->getResult();