Laravel eloquent:使用模型获取数据,其中Pivot等于自定义字段

时间:2014-09-20 18:11:38

标签: laravel orm eloquent

我有一个雄辩的对象Performer,有专辑和专辑有图像

这是设置:

模特演员 - >专辑():

public function albums()
{
  return $this->belongsToMany('Album','performer_albums','performer_id','album_id');
}

模型相册 - > images()

public function images()
{
  return $this->belongsToMany('Image','album_images','album_id','image_id')->withPivot(['type','size']);
}

我将表演者对象存储为:

$performer = Performer::where...->first();

现在我需要让Performer的相册中包含size为'大'

的图片

为了避免嵌套查询,我可以使用with()吗?

我试过

$performer->albums()
          ->with('images')
          ->wherePivot('size','large')
          ->get();

但laravel告诉我,它试图使用wherePivot for Performer-Album关系(M-2-M)


PS。我也知道我可以这样做,

$performer = Performer::with('albums')
                      ->with('albums.images')
                      ->.....-conditions for additional fields in album_images....
                      ->get();

但问题仍然存在。

1 个答案:

答案 0 :(得分:3)

您需要eager load constraints

$performer->albums()
  ->with(['images' => function ($q) {
      $q->wherePivot('size','large');
  }])
  ->get();

顺便说一下,不,你不能这样做:

Performer::with('albums')
  ->with('albums.images')
  ->.....-conditions for additional fields in album_images....
  ->get();

而你可以这样做:

Performer::with(['albums.images' => function ($q) {
     $q->   .....-conditions for additional fields in album_images....
  }])->get();