Limiting the result of nested relationship in Laravel

末鹿安然 提交于 2021-01-29 05:10:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!