Laravel如何查询透视表



我有三个模型:专辑作者贡献

与专辑和作者有很多对很多的关系

// Album model
function authors()
{
return $this->belongsToMany(Author::class);
}
// Author model
function albums()
{
return $this->belongsToMany(Album::class);
}

"作者"one_answers"贡献"之间存在着多对多的关系。

一个作家可能会为一张专辑做出一些贡献。

// 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_id">在数据透视表album_author上。我正试图利用这个领域来获得一位作家对某张专辑的贡献。

在作者页面,我想列出他的专辑和他的贡献(每张专辑(。

// 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;
}

如何检索当前作者对相册的贡献?如何查询枢轴";白蛋白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;

最新更新