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

Laravel 10中Eloquent belongsTo关联无法正常使用问题求助

Laravel 10 Eloquent BelongsTo关联返回Null问题解决

问题根源及修正步骤:

  1. Fragment模型关联外键参数错误
    你在Fragment模型的belongsTo关联里,错误地将第二个参数传成了当前模型的主键FragmentID,而正确的外键应该是关联到FragmentGroup的字段FragmentGroupID。

修正后的Fragment模型代码:

class Fragment extends Model {
    public function fragmentGroup(): BelongsTo
    {
        return $this->belongsTo(FragmentGroup::class, 'FragmentGroupID');
    }
}
  1. FragmentGroup模型关联方法名与类名笔误
  • 关联方法名medicine_type完全不符合“一个FragmentGroup对应多个Fragment”的逻辑,应改为fragments;
  • 代码里的Fragment:class存在语法错误,冒号应为两个(::),正确写法是Fragment::class。

修正后的FragmentGroup模型代码:

class FragmentGroup extends Model  {
    public function fragments(): HasMany
    {
        return $this->hasMany(Fragment::class, 'FragmentGroupID');
    }
}
  1. 数据库表名拼写错误
    数据库中的表名写成了FragementGroup(少了一个字母r),正确表名应为FragmentGroup,需确保表名与模型对应的数据库表一致。

优化建议

调用关联时建议使用预加载避免N+1查询问题:

$fragment = Fragment::with('fragmentGroup')->find(1);
return $fragment->fragmentGroup->name;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 09:17:40