Laravel 3表之间的雄辩关系 [英] Laravel Eloquent Relation between 3 table
问题描述
我需要一些帮助来建立音乐库数据库.
我有3张桌子相册,艺术家,角色
我希望一位艺术家为每张专辑都扮演一个角色.
像:
艺术家1担任专辑1的作曲家,但还担任专辑2的编曲者,或担任专辑3的作曲家和编曲者
I need some help make a music library database.
I have 3 tables albums, artists, roles
I want an artist to have a role for each album.
like :
artist 1 work as Composer for album 1, but also work as arranger on album 2 or work as composer and arranger on album 3
我已经尝试过了
数据库应该如何显示?什么是类型关系?
how should database looks? and what type relationship is?
推荐答案
在当前架构中,您将无法基于专辑标记艺术家的角色.
由于表中没有关系来定义artist_role
表中的条目用于特定专辑.因此,我建议创建一个包含 role_id
, artist_id
和 album_id
的中间表.
若要将此中间表与laravel的manyToMany
关系一起使用,可以在模型中定义将一个属性指定为数据透视表属性的方法.
In your current schema, you will not be able to tag the role of the artist on basis of album.
As there is no relation in your tables to define that the entry in artist_role
table is for specific album. So, what I would suggest is to create an intermediate table containing the role_id
,artist_id
and album_id
.
To use this intermediate table with laravel's manyToMany
relationship, you can define the methods in your models specifying one attribute as pivot attribute.
例如在艺术家模型中:
public function Roles(){
return $this->belongsToMany('App\Roles')->withPivot('album_id');
}
public function Albums(){
return $this->belongsToMany('App\Albums')->withPivot('role_id');
}
也为其他模型定义类似的方法.
Define similar methods for other Models also..
要获得Artist
在专辑中的作用,请在Album
模型中添加以下方法:
For getting Artist
with its role in Album add following method in the Album
model:
public function Artists(){
return $this->belongsToMany('App\Artist')->withPivot('role_id');
}
对于角色,请添加以下方法:
For roles add following method:
public function Roles(){
return $this->belongsToMany('App\Roles')->withPivot('artist_id');
}
这篇关于Laravel 3表之间的雄辩关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!