Laravel如何查询数据透视表?

问题描述

我有三种模式:相册作者贡献

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...