繁体   English   中英

Laravel如何查询pivot表?

[英]Laravel how to query pivot table?

我有三个模型: AlbumAuthorContribution

专辑和作者之间存在多对多关系

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

如您所见,我在 pivot 表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;
}

如何检索当前作者对专辑的贡献? 如何查询pivot“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;

暂无
暂无

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

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