[英]count constraint not working laravel eloquent nested relations
我試圖將計數約束放在laravel雄辯的嵌套關系上,但它沒有按預期工作。
這里的場景是:fetch酒店那些有日期范圍的房間
$hotels = Hotel::where('destination_id', $destinationId) - > with(['rooms' = > function ($query) use($totalNights, $check_in, $check_out) { $query - > with([ 'dateWisePricing' = > function ($dateWisePricing) use($check_in, $check_out) { $dateWisePricing - > where('date', '>=', $check_in); $dateWisePricing - > where('date', '<', $check_out); $dateWisePricing - > orderBy('date'); } ]); $query - > has('dateWisePricing', '>=', $totalNights); } ]) - > has('rooms.dateWisePricing') - > get();
在這里,它將返回在日期范圍內無法使用的房間(即dateWisepricing im empty collection)
請幫忙
最好使用whereHas
而不是僅查詢with
方法。 但最好的選擇是使用這樣的連接查詢它:
$hotels = Hotel::select('hotels.*')
->with(['rooms.dateWisePricing' => function ($dateWisePricing) {
$dateWisePricing - > orderBy('date');
}])
->join('rooms', 'rooms.hotel_id', '=', 'hotels.id')
->join('date_wise_pricings', 'date_wise_pricings.id', '=', 'rooms.date_wise_pricing_id')
->where('date_wise_pricings.date', '>=', $check_in)
->where('date_wise_pricings.date', '<', $check_out)
->where('destination_id', $destinationId)
->groupBy('hotels.id')
->get();
這種方法將查詢所有不可用的記錄。
注意
我使用的提示: hotels
, rooms
和date_wise_pricings
表名,但事實上我不知道你怎么稱呼他們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.