简体   繁体   English

计数约束不工作laravel雄辩的嵌套关系

[英]count constraint not working laravel eloquent nested relations

I'm trying to put count constraint on laravel eloquent nested relations, but it's not working as expected. 我试图将计数约束放在laravel雄辩的嵌套关系上,但它没有按预期工作。

Here scenario is :fetch Hotels those have rooms which are available in date range 这里的场景是: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();

here it's returning the rooms which are not avuable in date range ( ie dateWisepricing im empty collection) 在这里,它将返回在日期范围内无法使用的房间(即dateWisepricing im empty collection)

any help please 请帮忙

It's better to use whereHas instead of only querying the with method. 最好使用whereHas而不是仅查询with方法。 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. 我使用的提示: hotelsroomsdate_wise_pricings表名,但事实上我不知道你怎么称呼他们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM