Eloquent belongsTo()关联返回空对象,无法获取Item的code属性怎么解决?
问题解决步骤
1. 修正ServiceItem模型的关联定义
关联无法生效的核心原因是belongsTo方法的第二个参数误用了占位值'foreign_key',需要替换为数据库中实际存储的外键字段名:
//ServiceItem model修正后代码 class ServiceItem extends Model { use HasFactory; public $fillable = ['service_id', 'item_id', 'values']; public function service() { // 第二个参数改为实际外键service_id return $this->belongsTo(Service::class, 'service_id'); } public function item() { // 第二个参数改为实际外键item_id return $this->belongsTo(Item::class, 'item_id'); } }
2. 控制器添加嵌套关联预加载
为了避免N+1查询性能问题,同时确保关联数据完整加载,修改控制器的查询代码,预加载serviceItems下嵌套的item关联:
public function index() { // 新增with方法预加载嵌套关联 $services = Service::with(['serviceItems.item'])->latest()->paginate(5); return view('services.index', compact('services')) ->with('i', (request()->input('page', 1) - 1) * 5); }
3. 修正Blade模板的关联调用方式
之前调用$serviceItem->item()加了括号,返回的是关联查询构造器对象而非关联数据,需要去掉括号使用动态属性获取关联模型实例,直接取code属性即可:
@foreach ($service->serviceItems as $serviceItem ) {{-- 直接获取code属性,加??判空避免无关联数据时报错 --}} {{ $serviceItem->item->code ?? '无对应Item数据' }} {{-- 如果需要输出整个Item对象的JSON,写法如下 --}} {{-- {{ json_encode($serviceItem->item) }} --}} @endforeach
内容的提问来源于stack exchange,提问作者hweiu321
相关产品推荐
相关产品推荐

