如何用Laravel Eloquent多层嵌套whereHas实现多级关联条件查询?
Laravel 多层嵌套whereHas关联查询实现
场景说明
数据库表关联规则:
- Ad表存在两个
hasMany类型的子关联:Media、time_slot
查询筛选要求:
- 目标Media关联的父级Ad,必须存在符合时间范围的
time_slot记录:time_slot.from≤ 当前时间,且time_slot.to≥ 当前时间 - Media自身
format字段等于指定值 - 随机返回1条匹配的Media记录
可直接运行的实现代码
// 可用Laravel自带now()辅助函数直接获取当前时间,无需手动生成 $today = now(); $frm = "指定的format值"; $media = Media::with('ad') ->whereHas('ad', function ($q) use ($today) { $q->whereHas('time_slot', function ($q2) use ($today) { // 仅按日期过滤保留whereDate,需要精确到时分秒直接用where即可 $q2->where('from', '<=', $today)->where('to', '>=', $today); }); }) ->where('format', $frm) ->inRandomOrder() ->firstOrFail();
注意事项
- 如果不需要用到返回结果中Ad的关联数据,可以去掉
with('ad')预加载,减少不必要的查询开销 firstOrFail()在无匹配数据时会抛出404异常,如果你需要无匹配时返回null,可以替换为first()
内容的提问来源于stack exchange,提问作者L.DZ
相关产品推荐
相关产品推荐

