Laravel eager load function limit [duplicate]
Asked Answered
C

3

2

I have a working function, however, I'd like to limit the number of treatments, per consultant, that are returned.

Working Example:

Clinic::where('user_id', Auth::id())
            ->with('consultants.specialism', 'consultants.treatments')
            ->first();

Proposed (but not working) example:

Clinic::where('user_id', Auth::id())
            ->with('consultants.specialism')
            ->with(['consultants.treatments' => function ($query) {
                $query->take(3);
            }])
            ->first();

Unfortunately, the take or limit function, limits it to the total number of treatments returned.

What I would like is to limit each consultant's treatments to a maximum of 3, not the total.

How can I achieve this please?

Coaction answered 15/1, 2017 at 18:21 Comment(2)
treatments should return a collection of treatments, right? Then you want to get only first 3... So what's the problem? ->take(3) does exactly that.Laubin
#33607588Fanestil
M
6

There is no native support for this in Laravel.

I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit

Use the HasEagerLimit trait in both the parent and the related model.

class Consultant extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Treatment extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then simply chain ->take(3) call to your eager-load query (which seems you already do).

Mezzorilievo answered 27/10, 2018 at 13:40 Comment(1)
This is a great package Jonas, it's solved an issue I had and I think some of your others may help me too! Thank youLesbos
C
1

You have two options, either fetch all related comments and truncate in php using something like Collection::map or replace the eager loading with a complex sub-query

Cymbre answered 15/1, 2017 at 23:21 Comment(0)
C
-1

Try this out

Clinic::where('user_id', Auth::id()) 
->with(['consultants' => function ($query) { 
    $query
    ->with(['specialism','treatments'])
    ->take(3); 
}]) ->first();

I'm on my phone. So excuse my code formatting.

Castilian answered 15/1, 2017 at 18:40 Comment(1)
The query returned from the above (where the limit is used) is select * from consultants where consultants.clinic_id in ('1') limit 3. So that would, in essence, limit to only 3 consultants, not 3 treatments per consultantCoaction

© 2022 - 2024 — McMap. All rights reserved.