我想做一个查询来获取模型的关系,并按照查询中的关系对父模型进行排序,如下所示:
$data = Accommodation::with([ 'accommodationRoomsLimited.discount', 'accommodationRoomsLimited', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
}])->when($bed_count, function ($q, $bed_count) {
$q->with([
'accommodationRoomsLimited' => function ($q) use ($bed_count) {
$q->where('bed_count', $bed_count);
}
]);
因此,当用户为i发送bed_count 3时,此查询仅显示bed_count为3的房间,如果不显示,则显示住宿,但将空房间作为关系。我想这样我的结果,如果房间没有3的bed_count,它不会自动显示结果的住宿。我该如何实现?谢谢。
答案 0 :(得分:0)
也许如果您使用whereHas
而不是with
,可以这样做:
$data = Accommodation::with([ 'accommodationRoomsLimited.discount', 'accommodationRoomsLimited', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
}])->when($bed_count, function ($q, $bed_count) {
$q->whereHas('accommodationRoomsLimited', function($query) use ($bed_count) {
$query->where('bed_count', $bed_count);
});
更新
if ($bed_count !== null) {
$data = Accommodation::whereHas('accommodationRoomsLimited', function($query) use ($bed_count) {
$query->where('bed_count', $bed_count);
})->with(['accommodationRoomsLimited.discount', 'accommodationRoomsLimited', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
}])->get();
} else {
$data = Accommodation::with([ 'accommodationRoomsLimited.discount', 'accommodationRoomsLimited', 'accommodationRoomsLimited.roomPricingHistorySearch' => function ($query) use ($from_date, $to_date) {
$query->whereDate('from_date', '<=', $from_date);
$query->whereDate('to_date', '>=', $to_date);
}])->get();
}
希望有帮助。