[英]Laravel Eloquent Relation between 3 table
在當前架構中,您將無法基於專輯標記藝術家的角色。
由於表中沒有關系來定義artist_role
表中的條目用於特定專輯。 因此,我建議創建一個包含role_id
, artist_id
和album_id
的中間表。
若要將此中間表與laravel的manyToMany
關系一起使用,可以在模型中定義將一個屬性指定為數據透視表屬性的方法。
對於,例如在Artist Model中 :
public function Roles(){
return $this->belongsToMany('App\Roles')->withPivot('album_id');
}
public function Albums(){
return $this->belongsToMany('App\Albums')->withPivot('role_id');
}
也為其他模型定義類似的方法。
為了使Artist
在專輯中發揮作用,請在Album
模型中添加以下方法:
public function Artists(){
return $this->belongsToMany('App\Artist')->withPivot('role_id');
}
對於角色,請添加以下方法:
public function Roles(){
return $this->belongsToMany('App\Roles')->withPivot('artist_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.