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?

  • `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. – Frondor Jan 15 '17 at 18:47
  • http://stackoverflow.com/questions/33607088/laravel-5-eager-loading-with-limit – sumit Jan 15 '17 at 23:33

3 Answers3

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).

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
0

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

Community
  • 1
  • 1
nCrazed
  • 1,025
  • 6
  • 20
-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.

Gayan
  • 3,614
  • 1
  • 27
  • 34
  • 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 consultant –  Jan 15 '17 at 19:05