【问题标题】:count constraint not working laravel eloquent nested relations计数约束不起作用 laravel 雄辩的嵌套关系
【发布时间】:2017-03-16 23:03:48
【问题描述】:

我正在尝试对 laravel 雄辩的嵌套关系施加计数约束,但它没有按预期工作。

这里的场景是:获取在日期范围内有空房的酒店

$hotels = Hotel::where('destination_id', $destinationId) - > with(['rooms' = > function ($query) use($totalNights, $check_in, $check_out) { $查询 - > 与([ 'dateWisePricing' = > 函数 ($dateWisePricing) 使用($check_in, $check_out) { $dateWisePricing -> where('date', '>=', $check_in); $dateWisePricing -> where('date', '&lt', $check_out); $dateWisePricing - > orderBy('date'); } ]); $query -> has('dateWisePricing', '>=', $totalNights); } ]) - > has('rooms.dateWisePricing') - > get();

这里返回的房间在日期范围内不可用(即 dateWisepricing im empty collection)

请帮忙

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    最好使用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();
    

    这种方法会查询出所有不可用的记录。

    注意

    我使用的 Metion:hotelsroomsdate_wise_pricings 表名,但实际上我不知道您如何称呼它们。

    【讨论】:

    • dayWisePricing 是房间而不是酒店的关系
    • 请您解释一下它与我之前的代码有何不同,因为它返回相同的结果并且约束也无法像以前那样工作
    • 好吧,如果你在with 内部有问题,那么你只能限制内部关系的结果(而不是酒店)。如果您使用连接,那么您可以查询出所有没有任何关系结果的记录。如果这不起作用,请检查 $check_in$check_out vars 的日期格式。
    • 无论如何我没有看到使用连接查询语句,但是一旦我将 check_in 和 check_out 约束放入 roos.dateWisepricing 中,它就会像以前一样返回结果而没有任何变化
    • 我的意思是说,在 2 个日期之间不可用的房间仍在结果集中出现。一个疑问在给定日期可用的房间的限制在哪里
    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 2023-04-07
    • 2019-08-13
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多