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

如何用Laravel Eloquent多层嵌套whereHas实现多级关联条件查询?

Laravel 多层嵌套whereHas关联查询实现

场景说明

数据库表关联规则:

  • Ad表存在两个hasMany类型的子关联:Media、time_slot

查询筛选要求:

  1. 目标Media关联的父级Ad,必须存在符合时间范围的time_slot记录:time_slot.from ≤ 当前时间,且time_slot.to ≥ 当前时间
  2. Media自身format字段等于指定值
  3. 随机返回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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:27:02