简体   繁体   English

Laravel 3表之间的雄辩关系

[英]Laravel Eloquent Relation between 3 table

I need some help make a music library database. 我需要一些帮助来制作音乐库数据库。
I have 3 tables albums , artists , roles 我有3张唱片艺术家角色
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 艺术家1担任专辑1的作曲家,但还担任专辑2的编曲或专辑3的作曲家和编曲

I have tried this 我已经试过了 数据库设计

how should database looks? 数据库应该如何显示? and what type relationship is? 什么是类型关系?

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. 由于表中没有关系来定义artist_role表中的条目用于特定专辑。 So, what I would suggest is to create an intermediate table containing the role_id , artist_id and album_id . 因此,我建议创建一个包含role_idartist_idalbum_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. 若要将此中间表与laravel的manyToMany关系一起使用,可以在模型中定义将一个属性指定为数据透视表属性的方法。

For, eg in Artist Model : 对于,例如在Artist Model中

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.. 也为其他模型定义类似的方法。

Update: 更新:

For getting Artist with its role in Album add following method in the Album model: 为了使Artist在专辑中发挥作用,请在Album模型中添加以下方法:

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');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM