Laravel Eloquent query build select min value

旧城冷巷雨未停 提交于 2020-01-03 05:37:16

问题


I am having the following query (trimmed) to list the rooms to user for booking:

$buildquery=Room::

        with(['hotel' => function ($query) {
            $query->where('status', 0);
        }])

        ->with('image')->with('amenities');

        if ($request->filled('location_id')) {
            $buildquery->Where('city', $request->location_id);
        }

        $buildquery->Where('astatus', 1)->Where('status', 0);

        $rooms = $buildquery->simplePaginate(20);

Actual query (not trimmed):

select `rooms`.*, 
(select count(*) from `amenities` inner join `amenities_room` on `amenities`.`id` = `amenities_room`.`amenities_id` where `rooms`.`id` = `amenities_room`.`room_id` and `amenities_id` in (?)) as `amenities_count` 
from 
`rooms` 
where `city` = ? and `price` between ? and ? and `astatus` = ? and `status` = ? having 
`amenities_count` = ? 
limit 21 offset 100

It lists all the rooms available in hotel. I need to select only one room for one hotel with least price.


回答1:


You can use order by

$buildquery->orderBy('COL_NAME', 'DESC')->get();

if you need only one you can use take(1)




回答2:


Hotel::with('room' => function($query) {
    $query->orderBy('price', 'asc')->first();
},
'room.images',
'room.roomTypes',
'room.amenities'])
->get();

You can do something like this to get structure like:

{
    'Hotel': {
        'Room': {
            'Images': {
                //
            },
            'roomTypes': {
                //
            },
            'amenities': {
                //
            }
        }
    }
}

Is that what you want?



来源:https://stackoverflow.com/questions/47908180/laravel-eloquent-query-build-select-min-value

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