问题描述
我有三种模式:相册,作者,贡献
专辑和作者之间存在多对多的关系
// Album model
function authors()
{
return $this->belongsToMany(Author::class);
}
// Author model
function albums()
{
return $this->belongsToMany(Album::class);
}
作者和贡献之间存在多对多的关系。
作者可能对专辑有几处贡献。
// Author model
public function contributions()
{
return $this->belongsToMany(Contribution::class)->withPivot('album_id');
}
// Contribution model
public function authors()
{
return $this->belongsToMany(Author::class)->withPivot('album_id');
}
如您所见,我在数据透视表album_author上使用了另一个字段“ album_id” 。我正在尝试使用该字段来获得给定专辑的作者贡献。
在作者页面上,我想列出他的专辑和他的贡献(每张专辑)。
// Author controller
public function show($id)
{
$author = Author::find($id);
$albums = Album::whereHas('authors',function ($query) use ($id) {
$query->where('authors.id',$id);
})
->with('authors.contributions') // How to query the pivot "album_id" here ?
->get();
return $albums;
}
如何检索当前作者对某专辑的贡献? 如何查询数据透视表“ album_id”?
解决方法
您是否尝试过使用wherePivot:
$albums = Album::whereHas('authors',function ($query) use ($id) {
$query->where('authors.id',$id);
})
->with(['authors.contributions'=>function($query)use($albumId){
$query->wherePivot('album_id',albumId);}])
->get();
return $albums;