M
M
Mo1she2019-02-14 08:25:36
Laravel
Mo1she, 2019-02-14 08:25:36

How to eagerly load a certain number of related models?

I have categories and news and use a many-to-many relationship. I need to make a request using eager loading to get all the categories so that each category has only three news items.
I'm trying to do this:

$categories = Category::with('news')->orderBy('id', 'ASC')->get();

But in this case, all news is requested.
Also tried this:
$categories = Category::with(['news' => function($query)
        {
            $query->limit(3);
    }])->orderBy('id', 'ASC')->get();

But in this case, only three news items are requested. But I need three pieces in each category.
Please tell me how to solve the problem. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2019-02-14
@Mo1she

Apparently not:

The limitand takequery builder methods may not be used when constraining eager loads.
https://laravel.com/docs/5.7/eloquent-relationship...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question