2014-02-13 6 views
0

구조 :Laravel의 관계 및 with?

**galleries** 

id 
location 
open_to_public 

**pictures** 
id 
title 
published 

**gallery_picture** 
gallery_id 
picture_id 

모델 :

class Galleries extends Eloquent { 

protected $table = 'galleries'; 

public function pictures(){ 

    return $this->belongsToMany('pictures', 'gallery_picture', 'gallery_id', 'picture_id'); 

} 

나는 사진의 위와 동일한 모델을 가지고있다.

내 질문은 그림 ID를 전달하고 전달 된 그림 ID의 갤러리에 속한 모든 그림을 가져와야합니다.

지금까지 내가 가진 :

Pictures::with('galleries')->whereId($id)->get(); 

그러나 이것은 단지 하나의 그림을 반환합니다.

+0

'Picture' 모델에'$ this-> hasMany ('갤러리') 함수가 있습니까? – Alex

+0

@ w0rldart 예 – panthro

답변

3

어제 묻는 질문과 비슷하게 컬렉션의 모든 hasMany 개체를 병합하는 것은 Laravel이 아직 수행하지 않은 작업입니다.

// we'll eventually have all pictures here 
$pictures = new \Illuminate\Database\Eloquent\Collection; 

// get all galleries of the given picture 
$galleries = Picture::find($id)->galleries; 

// iterate through the galleries and add their pictures to our large set 
foreach ($galleries as $gallery) { 
    $pictures->merge($gallery->pictures); 
} 

그것은 belongsToMany 관계가 아니라면 단순히 Gallery hasMany Picture 다음 한 줄의 코드가 일한 것 Picture belongsTo Gallery : 당신은 당신의 자신의 루프를 작성해야

$pictures = Picture::find($id)->gallery->pictures; 

을하지만,이 경우에 해당 그림은 속한 갤러리가 하나 있어야합니다.