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

Laravel模型通过hasManyThrough关联三表,如何获取任务名称?

问题分析

你当前使用的hasManyThrough关联仅能获取到最终关联的resources模型数据,中间表Tasks的字段不会被自动加载,因此无法直接获取taskName。这种关联方式适用于跨表获取间接关联的最终模型集合,而非同时获取中间表与最终表的字段。

解决方案

通过嵌套预加载的方式,先关联PhaseTasks与Tasks,再关联Tasks与resources,即可同时获取阶段ID、任务名称和资源名称。

1. 修正模型关联

PhaseTasks 模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class PhaseTasks extends Model
{
    protected $table = 'PhaseTasks';
    // 关联表无自增主键,需关闭自动递增
    public $incrementing = false;
    protected $primaryKey = null;

    // 关联Tasks表
    public function task()
    {
        return $this->belongsTo(Tasks::class, 'taskId', 'taskId');
    }
}

Tasks 模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Tasks extends Model
{
    protected $table = 'Tasks';

    // 关联resources表
    public function resource()
    {
        return $this->belongsTo(Resources::class, 'defaultResource', 'id');
    }
}

Resources 模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Resources extends Model
{
    protected $table = 'resources';
}

2. 控制器查询与数据输出

// 预加载关联的任务和资源
$phaseData = PhaseTasks::with('task.resource')->where('phaseId', 1)->get();

// 遍历输出目标格式
foreach ($phaseData as $item) {
    echo "阶段ID: {$item->phaseId}, 任务名称: {$item->task->taskName}, 资源名称: {$item->task->resource->name}\n";
}

输出结果

阶段ID: 1, 任务名称: Do a thing, 资源名称: Engineering
阶段ID: 1, 任务名称: Do another thing, 资源名称: Engineering

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:15:32