【发布时间】:2020-09-28 14:28:27
【问题描述】:
我希望有人可以在这里帮助我,因为这让我很头疼。
我有两个模型,成分和 Uom(计量单位)。
在我拥有的成分中:
public function uom() {
return $this->belongsTo(Uom::class, 'uom');
}
每种成分只有一个计量单位。数据库中的 uom 列是保存度量单位 id 的列。
在 Uom 我有:
public function ingredients() {
return $this->hasMany(Ingredient::class);
}
每个度量单位可以有很多成分。
在成分表迁移中,我已将外键设置如下:
$table->foreign('uom')->references('id')->on('uoms')->onDelete('cascade');
有人可以告诉我为什么在下面的foreach中我得到了
Trying to get property 'name' of non-object
刀片代码:
@foreach ($ingredients as $ingredient)
<tr>
<td>{{$ingredient->name}}</td>
<td>{{$ingredient->uom->name}}</td>
<td>{{$ingredient->user->name}}</td>
</tr>
@endforeach
$ingredient->user->name 完美地引用了“added_by”列,所以我不知道为什么 uom 不起作用。
提前感谢您的帮助,我希望我只是忽略了一些愚蠢的事情
【问题讨论】:
-
发生这种情况的原因是因为您显然有一种成分没有任何与之相关的单位。也许这有点帮助。 Dilip 提供的解决方案增加了这种关系的后备。
-
我得到了回退,这太棒了。不是我以前知道的。问题是我在数据库中的所有数据在成分表的 uom 列中都有整数。所以不知何故,它没有检测到我假设的外键分配
-
啊,我明白了。我会添加我的答案!
标签: laravel eloquent relationship