我的模型与外键,受保护的表有关系。
这是我的模特:
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');
}
}
比相关型号Comment.php:
<?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, “日期”: “2017年5月21日”, “公司”: “三菱”, “model_year_en”:2005" }
在视图中我需要获取公司信息,我这样做:
@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
工作?
谢谢,来自laracasts的Snapey
当你这样做
@foreach ($comments as $comment)
<td> {{ $comment->lot->company }}</td>
@endforeach
你依靠每一条评论都有很多,而且每一个人都有一家公司
您可以使用它来防止空属性
@foreach ($comments as $comment)
<td> {{ $comment->lot->company or '---'}}</td>
@endforeach
然后即使批次没有公司,循环也会继续