W
W
WebDev2016-09-05 23:51:06
Laravel
WebDev, 2016-09-05 23:51:06

Laravel limit for with?

Category::with(['products' => function($query) {
    $query->take(3);
}])->where('type', 1)->get();

This is how I try to select 3 products for each category. But the code doesn't work.
How to specify a limit for with?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2016-09-06
@Kraky

You cannot do this in Eloquent. In fact, you only get 3 categories. Therefore, if there are not many products, you can select categories, and then make a map through the collection and remove unnecessary products. Or you can do something like:

$categories = Category::where('type', 1)->get();
$categories->each(function($category) {
    $category->products()->take(3)->get();
});

This will cause additional requests for each category...

E
Evgeny Bukharev, 2020-08-14
@evgenybuckharev

This package helped
https://github.com/staudenmeir/eloquent-eager-limit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question