,循环也将继续
我在模型中与前键,受保护表有一个关系。
这是我的模型:
lot.php:
<?php
namespace App;
class Lot extends Model
{
protected $table = 'auct_lots_full';
protected $primaryKey = 'lot_id';
public function comments()
{
return $this->hasMany(Comment::class,'lot_id', 'lot_id');
}
}
比相关模型注释:
<?php
namespace App;
class Comment extends Model
{
public function lot()
{
return $this->belongsTo(Lot::class, 'lot_id', 'lot_id');
}
}
在我看来,我尝试这样做:
@foreach ($comments as $comment)
<dt>{{ $comment->lot }}</td>
@endforeach
结果:
{" lot_id":391959148," date":" 2017-05-21"," Company":" Mitsubishi"," Model_year_en":2005"}
从视图中,我只需要获取 company 信息,我会这样做:
@foreach ($comments as $comment)
<td> {{ $comment->lot->company }}</td>
@endforeach
此结果错误:
尝试获取非对象的属性
我尝试这样做:
@foreach ($comments as $comment)
<td>
@foreach($comment->lot as $lot)
{{ $lot->company }}
@endforeach
</td>
@endforeach
也会给出错误:
尝试获取非对象的属性
如何获得$comment->lot->company
工作?
谢谢,
snapey当您这样做
@foreach ($comments as $comment)
<td> {{ $comment->lot->company }}</td>
@endforeach
您依靠每个评论都有很多,每个人都有公司
您可以使用它来防止空属性
@foreach ($comments as $comment)
<td> {{ $comment->lot->company or '---'}}</td>
@endforeach
那么,即使批次没有公司