1

I have a nested relationship that I want to set a condition and a limit.

$data = Accommodation::with('accommodationFacilities', 'city')
    ->take(10)
    ->with('accommodationRooms.roomPricingHistory')
    ->limit(2)
    ->where('is_deleted', 0)
    ->paginate(10);

Now I have a nested relation on line 2 that I want to limit this relation by: roomPricingHistory.

The code limits the parent relation which is: accommodationRooms.

Any idea how I can limit the child relation and how can I set an if for it so if a column is === 0 this row should be loaded.

Karl Hill
  • 12,937
  • 5
  • 58
  • 95
Farshad
  • 1,830
  • 6
  • 38
  • 70
  • Does this answer your question? [Laravel eager loading with limit](https://stackoverflow.com/questions/33607088/laravel-eager-loading-with-limit) – miken32 Dec 07 '21 at 17:42

1 Answers1

1

You could try constraining the eager loading

$data = Accommodation::with('accommodationFacilities', 'city')
    ->take(10)
    ->with(['accommodationRooms.roomPricingHistory' => function($query){
        $query->limit(2)
    }])
    ->limit(2)
    ->where('is_deleted', 0)
    ->paginate(10);

Docs: https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

Ian C
  • 141
  • 1
  • 10
  • when i use 2 nothing loads but when i increase number to 12 for example 3 units appear any way i think i must look more for it – Farshad May 07 '19 at 12:44