Laravel Eloquent查询构建选择最小值

问题描述 投票:0回答:2

我有以下查询(修剪)列出用户预订的房间:

$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);

实际查询(未修剪):

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

它列出了酒店的所有房间。我需要为价格最低的一家酒店选择一间客房。

php mysql eloquent laravel-5.5
2个回答
0
投票

你可以use order by

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

如果你只需要一个,你可以使用take(1)


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

你可以做这样的事情来获得如下结构:

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

那是你要的吗?

© www.soinside.com 2019 - 2024. All rights reserved.