问题
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