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

Laravel模型关联问题:如何获取用户关联的Testseries查询构造器

解决Laravel多关联模型的Testserie查询问题

直接在User模型中定义testseries()方法,返回Testserie的查询构造器,通过用户关联的设备ID做筛选:

// app/Models/User.php
public function testseries()
{
    return Testserie::whereIn('device_id', $this->devices()->select('id'));
}

调用时直接使用这个方法,既能拿到Testserie的查询构造器,也能随时追加查询条件:

// 获取用户关联的所有Testserie模型
$userTestseries = $user->testseries()->get();

// 追加where条件,比如筛选已完成的测试系列
$completedTests = $user->testseries()->where('status', 'completed')->get();

为什么之前的方法不生效?

  • load/with:这两个是预加载关联的方法,返回的是包含Device模型的集合,嵌套着testseries关联,不符合你要直接获取纯Testserie模型的需求。
  • pluck:只能提取单个字段值,无法返回完整的Testserie模型集合。
  • 调用$devices->getRelation('testseries'):当$devices是空集合时,这个操作没有基于用户的设备关联做约束,导致返回全部数据,逻辑上不成立。

如果想要更贴合Laravel关联风格的写法,也可以用手动关联中间表的方式:

// app/Models/User.php
public function testseries()
{
    return $this->hasManyThrough(
        Testserie::class,
        Device::class,
        'id',
        'device_id',
        'id',
        'id'
    )->join('device_user', 'devices.id', '=', 'device_user.device_id')
      ->where('device_user.user_id', $this->id);
}

两种写法都能满足你的核心需求:返回查询构造器、支持后续追加条件、结果为纯Testserie模型集合,第一种whereIn的写法更简洁直观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:55:22