且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Laravel 3表之间的雄辩关系

更新时间:2023-09-24 15:30:28

在当前架构中,您将无法基于专辑标记艺术家的角色.
由于表中没有关系来定义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');
}