如何在Laravel中的多对多关系中添加“别名”?

问题描述 投票:0回答:1

我和演员之间有多对多的关系。

如何在连接时添加他的stage name?我有一个演员表,一个剧院表和一个表,用于连接多个到多个调用actor_theater_play,我连接ID。

我的目标是显示John Doe is know for his roles:然后列出Name of Play - Character Name

laravel laravel-5 many-to-many
1个回答
1
投票

在您的Actor模型的剧院游戏关系中,请确保使用->withPivot()方法指定您希望通过关系附加哪些枢轴字段:

public function theaterPlays() {
    return hasMany(\App\TheaterPlay::class)->withPivot('stage_name');
}

然后,您就可以在列表中访问(Laravel刀片示例):

@foreach($actor->theater_plays as $theater_play)
    {{ $theater_play->name . ' - ' . $theater_play->stage_name }}
@endforeach
© www.soinside.com 2019 - 2024. All rights reserved.