I have a basic table article linked to a table category by id (classic), I would like to make a doctrine request to retrieve only 5 articles by category (for all categories)
This request return me all articles of categories, I just want 5 for each
public function getArticlesAndCategs(){
$qb = $this->createQueryBuilder('c')
->orderBy('c.id','DESC')
->leftJoin('c.articles', 'a')
->addSelect('a')
->addOrderBy('a.id','DESC')
->getQuery();
return $qb->execute();
}
Can you help me for that?
thank you
This is no easy task unfortunately. At least I haven’t found a satisfying solution yet (satysfying for me 😉 ).
Three things you can do:
Iterate through the categories and retrieve 5 posts for each category. This of course cause that many db request as many you have categories.
Return all the categories with joined posts and iterate inside php. The drawback – you’ll return all the posts, so if you have many, this can mean a lot of memory used.
If you don’t have to stick to Doctrine you can try the solution from here: mySQL Returning the top 5 of each category