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

Laravel关联模型with方法加载异常:仅返回ID未返回名称

问题

我有三张数据表:contracts、details、extra。每个contract对应一个detail,details表通过外键contractId与contracts表关联。details表包含5个关联自extra表的字段(比如Color)。我已经在Contract模型定义了hasOne关联,在Detail模型定义了belongsTo关联,这两个关联都能正常工作。

我在Detail模型中定义了以下关联,用来通过Detail模型获取Contract对应的颜色:

public function carColor(): BelongsTo
{
    return $this->belongsTo(Extra::class, "ColorCode", "id")->where('type', Extra::COLOR->value);
}

但使用下面的代码预加载关联模型时,仅返回了ID,没有返回name字段:

return ThirdPartyContract::where('id', $id)
    ->with(['detail' => function ($query) {
        $query->with(['carColor' => function ($query) {
            $query->select('name');
                }]);
            }])
        ->with('people')
        ->get();
解决方案

问题出在预加载carColor时只选择了name字段。Laravel处理belongsTo关联时,需要关联的主键字段(即Extra表的id)来匹配Detail表的ColorCode,如果不把id包含在select语句里,Laravel无法正确关联模型,只会返回匹配的ID值,无法返回其他字段。

修改预加载的select语句,把id字段加入即可:

return ThirdPartyContract::where('id', $id)
    ->with(['detail' => function ($query) {
        $query->with(['carColor' => function ($query) {
            // 必须包含关联主键id,否则无法匹配关联模型
            $query->select('id', 'name');
                }]);
            }])
        ->with('people')
        ->get();

另外要确认:Detail模型carColor关联中指定的自定义外键ColorCode,确实与Extra表的id字段对应,且数据表中的关联数据是匹配的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:57:38