2014-09-20 72 views
0

我有了相册和相册图片有雄辩的对象演员Laravel雄辩:与模型得到的数据wherePivot等于自定义字段

这里是设置:

型号Performer->专辑():

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

模型相册 - >图像()

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

我已经表演对象的形式存储:

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

现在我需要得到演员的相册,其中size是“大”

因此,为了避免嵌套查询图像,可我用()?

我试图

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

但laravel告诉我这是试图用wherePivot的表演专辑关系(M-2-M)


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

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

但问题依然如此。

回答

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();