问题
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.
回答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
来源:https://stackoverflow.com/questions/55991576/limiting-the-result-of-nested-relationship-in-laravel