laravel 中的数据透视表:我如何访问不仅仅是 ID 的内容?

Pivot tables in laravel: how do I access more than just the ids?

我正在 laravel 5.1 中进行我的第一个项目,一个家谱。对于家庭电影,我有一个视频 table 和一个人 table,并且我有 person_video 枢轴 table 来跟踪每个视频中出现的人。 table 也有一个描述列,用于提示“0:29-0:35,朝向前方,戴着帽子”。

Video.php 有:

public function people()
{
    return $this->belongsToMany('App\Person', 'person_video');
}

然后当我显示给定视频中的人物时,我有:

@foreach($video->people as $person)
    @include ('person.partials._person_link', ['person' => $person]):
    {{$person->pivot}} 
@endforeach

信息显示给人们,但对于 pivot 它只给我 video_id 和 person_id 的值:

 {"video_id":6,"person_id":4} 

它不包括描述(或时间戳,但我在这里不需要)。我怎样才能让描述随行?我希望能够使用 {{$person->pivot->description}},但是当我尝试这样做时,没有任何显示。

参见LaravelDocs/Eloquent/Working with pivot tables

By default, only the keys will be present on the pivot object. If your pivot table contains extra attributes, you must specify them when defining the relationship:

return $this->belongsToMany('Role')->withPivot('foo', 'bar');

Now the foo and bar attributes will be accessible on our pivot object for the Role model.

所以你的 Video::people() 看起来像这样:

public function people()
{
    return $this->belongsToMany('App\Person', 'person_video')->withPivot('description');
}

那么您应该可以从您的视图中访问 {{$person->pivot->description}}