Let’s say, we have 6 post categories, that have more than 100 posts each, in order to get these 6 categories with 20 random posts from each there are two ways to do this:
- Through loop, with
limit(20)this will create 7 queries
(n+1), but will delegate
random()to DB layer, as a result we get all the data already prepared.
- Through eager loading, that will create 2 queries, but will request all the posts that are connected to categories, then we just have to get 20 random from array and limit all that. It can be done in multiple ways.
So what is better?