dink's avatar
Level 1

Limit number of queries when fetching posts from categories

I'm trying to fetch categories (which I call collections) with 4 posts each. The below code works, but it's querying all the posts first, then only takes 4. With a lot of posts in each category, that's a lot of db queries. Is there a way to do it better?

My current Controller:

// CollectionController

public function index()
{

$collections = Collection::with('posts')->take(12)->get()->map(function($collection) {
  $collection->setRelation('posts', $collection->posts->take(4));
  return $collection;
});

return view('collections.index', compact('collections'));

}

And my model relations:

// Post Model

  public function collection()
  {
    return $this->belongsTo(Collection::class);
  }

// Collection Model

  public function posts()
  {
    return $this->hasMany(Post::class);
  }
0 likes
5 replies
dink's avatar
Level 1

@Snapey Yes, that's correct.

Lary, The AI bot suggested the following:

    $collections = Collection::with(['posts' => function ($query) {
      $query->take(4);
    }])->take(12)->get();

But for some reason it fetched 4 posts from only one collection, and gave empty arrays for all the others. I marked it as "Not useful", and it deleted the suggestion entirely along with my response. I wish it could stay up for reference.

Thanks for the suggestion, I'll check out the package.

Snapey's avatar

@dink lary is not always correct, especially in this case

1 like

Please or to participate in this conversation.