I'm trying to put count constraint on laravel eloquent nested relations, but it's not working as expected.
Here scenario is :fetch Hotels those have rooms which are available in date range
$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();
here it's returning the rooms which are not avuable in date range ( ie dateWisepricing im empty collection)
any help please
It's better to use whereHas
instead of only querying the with
method. But the best option is to query it out with joins like this:
$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();
This approach will query out all not available record.
Attention
Metion that I use: hotels
, rooms
and date_wise_pricings
table names but in fact I dont know how you call them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.