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

Laravel使用whereHas查询嵌套关联时如何校验最新记录type等于1

实现方案

你直接在whereHas闭包里加latest()再匹配type的写法是无效的,whereHas只会判断是否存在满足查询条件的关联记录,不会识别排序规则,所以只要有任意一条符合区间的type=1记录就会返回,不是你要的「最新一条满足」的逻辑。

下面给出两种可行实现:

方案1:子查询匹配最新记录ID(全版本兼容)

$model->users()
    ->whereHas('relation', function ($query) use ($dates) {
        $query->whereBetween('created_at', $dates)
              ->where('type', 1)
              ->where('id', function ($subQuery) {
                  // 子查询取对应用户最新的关联记录ID
                  $subQuery->select('id')
                      ->from('relations') // 替换为你的关联表实际表名
                      ->whereColumn('relations.user_id', 'users.id') // 替换为实际的外键关联字段
                      ->latest('created_at')
                      ->limit(1);
              });
    });

方案2:预定义latestOfMany关联(Laravel 8.42+ 推荐)

首先在User模型中定义单条最新关联:

// App/Models/User.php
public function latestRelation()
{
    // 替换为你实际的关联类名
    return $this->hasOne(Relation::class)->latestOfMany();
}

查询时直接调用该关联即可:

$model->users()
    ->whereHas('latestRelation', function ($query) use ($dates) {
        $query->whereBetween('created_at', $dates)
              ->where('type', 1);
    });

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:57:00