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

Laravel 9中如何通过Objective表的set_id获取Objective_Sets的名称

在Laravel 9中通过关联获取objective_sets的名称

方法一:使用Eloquent关联(推荐)

1. 在Objective模型中定义关联关系

打开app/Models/Objective.php,添加关联方法,建立与ObjectiveSet模型的关联:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Objective extends Model
{
    // ... 其他已有代码

    public function objectiveSet()
    {
        // 关联ObjectiveSet模型,外键为set_id,对应objective_sets表的id字段
        return $this->belongsTo(ObjectiveSet::class, 'set_id', 'id');
    }
}

确保已创建ObjectiveSet模型(对应objective_sets表):

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ObjectiveSet extends Model
{
    protected $table = 'objective_sets'; // 遵循Laravel命名规则可省略,显式声明更清晰
}

2. 加载关联数据查询

修改查询代码,用with()预加载关联数据,即可获取对应集合名称:

$sets = Objective::where('subject_id', $id)->with('objectiveSet')->get();

返回结果会包含objective_set字段(默认蛇形命名),示例结构:

[
    {
        "id": 1,
        "subject_id": 1,
        "set_id": 1,
        "file": "1660481752_data.xlsx",
        "created_at": "2022-08-14T12:55:52.000000Z",
        "updated_at": "2022-08-14T12:55:52.000000Z",
        "objective_set": {
            "id": 1,
            "name": "集合1名称",
            "created_at": "...",
            "updated_at": "..."
        }
    }
]

若仅需name字段,可通过闭包筛选关联字段(必须保留id用于关联匹配):

$sets = Objective::where('subject_id', $id)
    ->with(['objectiveSet' => function ($query) {
        $query->select('id', 'name');
    }])
    ->get();

方法二:使用数据库JOIN查询

如果不需要Eloquent关联,可直接通过JOIN语句将name字段合并到结果中:

$sets = Objective::select('objectives.*', 'objective_sets.name as set_name')
    ->join('objective_sets', 'objectives.set_id', '=', 'objective_sets.id')
    ->where('objectives.subject_id', $id)
    ->get();

返回结果会直接包含set_name字段,示例结构:

[
    {
        "id": 1,
        "subject_id": 1,
        "set_id": 1,
        "file": "1660481752_data.xlsx",
        "created_at": "2022-08-14T12:55:52.000000Z",
        "updated_at": "2022-08-14T12:55:52.000000Z",
        "set_name": "集合1名称"
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:54:24