You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel:如何在Blade模板中获取带日期过滤的关联Slots数据

解决方案

你当前的whereHas只是用来筛选存在符合日期条件Slot的Product,但并不会约束关联Slot的加载结果;而调用$product->slots()会触发全新的查询,自然不会带上之前的日期过滤条件。要实现需求,只需在查询时同时预加载并过滤关联的Slot,具体步骤如下:

1. 修改查询代码,结合with()预加载过滤后的Slot

将原查询改为同时使用whereHas和with,并在with的闭包中加入相同的日期过滤条件:

Product::whereHas('slots', function ($query) {
        $query->whereDate('start_time', '=', $this->booking_date);
    })
    ->with(['slots' => function ($query) {
        $query->whereDate('start_time', '=', $this->booking_date);
    }])
    ->get();

这样查询时会一次性加载符合条件的Product,以及每个Product对应的指定日期的Slot,避免N+1查询的同时,确保关联数据是过滤后的结果。

如果不想重复写过滤逻辑,可以把条件抽成回调函数复用:

$slotFilter = function ($query) {
    $query->whereDate('start_time', '=', $this->booking_date);
};

Product::whereHas('slots', $slotFilter)
    ->with(['slots' => $slotFilter])
    ->get();

2. 在Blade模板中遍历预加载的Slot

模板中直接访问$product->slots(注意是属性,不是方法slots()),这个属性就是预加载好的、符合日期条件的Slot集合:

@foreach($product->slots as $slot)
    <p>{{ $slot->start_time }}</p>
@endforeach

内容的提问来源于stack exchange,提问作者user1666453

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 21:12:40