因此,我需要一种在某些条件下搜索房间的方法,这来自主页中的表单,其中用户通过城市,room_type和check_in_date,check_out_date和datepicker进行搜索
我要带rooms WHERE (input.check_in_date
NOT BETWEEN (bookings.check_in_date AND bookings.check_out_date) AND input.check_in_date NOT BETWEEN (bookings.check_in_date AND bookings.check_out_date) OR NOT IN bookings) WHERE rooms.city = input.city AND rooms.room_type = input.room_type
我花了很多时间进行查询,但是我完全呆在这里了, 我发现现在使用laravel查询生成器要容易得多。
$check_dates = explode(' - ', $request->datetimes);
$check_in = date('Y-m-d', strtotime($check_dates[0]));
$check_out = date('Y-m-d', strtotime($check_dates[1]));
$room_types = RoomTypes::all();
$rooms = DB::table('rooms')
->leftJoin('bookings', function ($join) use ($check_in, $check_out) {
$join->on('rooms.id', '=', 'bookings.rooms_id')
->where(function ($q) use ($check_in, $check_out) {
$q->whereNotBetween('bookings.check_in_date', [$check_in, $check_out])
->whereNotBetween('bookings.check_out_date', [$check_in, $check_out]);
})->orWhere(function ($q) {
$q->whereNotIn('rooms.id', DB::table('bookings')->select('rooms_id'));
});
})
->where('rooms.city', $request->city)
->where('rooms.room_type', $request->room_type)
->get();
查询是这个
SELECT * FROM `rooms` LEFT JOIN `bookings` ON `rooms`.`id` = `bookings`.`rooms_id`
WHERE ((`bookings`.`check_in_date` NOT BETWEEN $check_in_date AND $check_out_date
AND `bookings`.`check_out_date` NOT BETWEEN $check_in_date AND $check_out_date)
OR `rooms`.`id` NOT IN (SELECT `rooms_id` FROM `bookings`)) AND `rooms`.`city` = $city AND `rooms`.`room_type` = $room_type
答案 0 :(得分:0)
我将使用雄辩的whereHas方法。 看起来像这样:
$rooms = Room::doesntHave('bookings')->orWhereHas('bookings', function ($query) use ($check_in, $check_out) {
$query->whereNotBetween('check_in_date', [$check_in, $check_out])
->whereNotBetween('check_out_date', [$check_in, $check_out]);
})
->where('city', $request->city)
->where('room_type', $request->room_type)
->get();
此代码未经测试。只是一个想法,它应该更容易解决;)
答案 1 :(得分:0)
$rooms = collect(DB::select("
SELECT * FROM `rooms` LEFT JOIN `bookings` ON `rooms`.`id` = `bookings`.`rooms_id`
WHERE `rooms`.`city` = '$request->city' AND `rooms`.`room_type` = '$request->room_type'
AND ((`bookings`.`check_in_date` NOT BETWEEN '$check_in' AND '$check_out'
AND `bookings`.`check_out_date` NOT BETWEEN '$check_in' AND '$check_out')
OR `rooms`.`id` NOT IN (SELECT `rooms_id` FROM `bookings`))
"));
使用这种方法解决了问题,现在的问题是:我们可以使用查询生成器来实现它还是对laravel而言太过定制