rudak
rudak

Reputation: 389

Symfony2, querybuilder's Doctrine request

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

Upvotes: 0

Views: 261

Answers (1)

Michal Trojanowski
Michal Trojanowski

Reputation: 12352

This is no easy task unfortunately. At least I haven't found a satisfying solution yet (satysfying for me ;) ).

Three things you can do:

  1. Iterate through the categories and retrieve 5 posts for each category. This of course cause that many db request as many you have categories.

  2. 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.

  3. If you don't have to stick to Doctrine you can try the solution from here: mySQL Returning the top 5 of each category

Upvotes: 2

Related Questions