'symfony 4 sort posts by number of likes
I am trying to sort my posts by the number of likes, I need help
this is the post entity
/**
* @ORM\OneToMany(targetEntity=PostLike::class, mappedBy="Publication")
*/
private $likes;
and this is the likes entity
class PostLike
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity=Publication::class, inversedBy="likes")
*/
private $Publication;
/**
* @ORM\ManyToOne(targetEntity=User::class, inversedBy="likes",cascade={"persist"})
*/
private $user;
Solution 1:[1]
You need to add your own method to the Post entity repository and write a dql query with the required sorting.
public function sortByCountLikes(){
return $this->createQueryBuilder('p')
->select('p, COUNT(l.id) AS HIDDEN like_count')
->leftJoin('p.likes', 'l')
->groupBy('p.id')
->orderBy('like_count', 'DESC')
->getQuery()
->getResult();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harvey Dent |
