拉拉维尔有问题 . 我已经在laravel中的模型级别创建了表和关系之间的关系但是如果我想向视图显示数据,则会出现错误: Property [category] does not exist on this collection instance.
这部电影的表格叫做:视频
具有类别的表称为:类别
数据透视表名为:category_video
Video model code:
public function categories()
{
return $this->belongsToMany('App\Category');
}
Categories model code:
public function videos()
{
return $this->belongsToMany('App\Video');
}
In controller i have this:
$slider_videos = Video::->orderBy('rating','desc')
->limit(5)
->get();
In view i try this:
@foreach($slider_videos as $slider_video)
{{$slider_video->category->name}}
@endforeach
我将在使用时添加: {{$slider_video->category}}
它显示单行的所有内容
顺便说一句,如何在模型中指定数据透视表的名称?
2 回答
类别是您需要循环它的集合:
即使只有一条记录与该关系相关联,
belongsToMany
也会返回一个集合 . 您需要在foreach
循环中访问它 . 像这样 .