2016-08-14 5 views
-1

restaurants을 갖는 users이 있고, 각각 restaurantcomments입니다.여러 관련 레코드에서 관련 레코드 세트 가져 오기 laravel?

그래서 user에 로그인하면 의 사용자 목록을 restaurants과 (과) 관련되었습니다.

나는 지금까지 무엇을 가지고 laravel 5.1

사용하고하는 것은 : 나는 BadMethodCallException를 얻을 수

$restaurants = $user->restaurants; 
     $comments = null; 
     foreach ($restaurants as $restaurant) { 
      if (!$comments){ 
       $comments = $restaurants->comments(); 
      } else{ 
       $comments = $comments->merge($restaurant->comments()); 
      } 
     } 

     $rows = $comments->paginate(15); 
     $count = $comments->count(); 

, 나는 이것을 laravel 방법을하고 있지 않다 생각합니다.

답변

2

Have Many Through를 시도해 보셨습니까? 사용자 모델에서
public function user_posts() { return $this->hasManyThrough('App\Comment', 'App\Restaurant'); } 그리고 컨트롤러에서 u는 쉽게 액세스 할 수있는 의견 여기 $comments = $user->user_posts(); 자세한 내용 : https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

+0

은 흠가 보인다 문제가된다면,'사용자'~'레스토랑'은'다 대다 '관계입니다 ... – surfer190

0

나는 대답을 찾았습니다 merge을 사용하려면 데이터 집합은 collection이어야합니다. 내 예에서 ->get();

:

그래서 당신은 사용할 필요가 컬렉션을 만들 수

$comments = $restaurants->comments()->get(); 

참고 : PAGINATE 기능 가고있다, 그것은 laravel의의 Nota 방법이다 Collection

+1

당신은 아직 할 수있는 페이지 매김을 할 수있는 대체 ->로) (얻을 -> PAGINATE가 (15) –

0

당신은, 당신이

$restaurant->comments 
// gives you objects 

을 거의 정확한 했어야했다

대신 (210)
$restaurant->comments() 
// gives you query builder 
// $restaurants->comments()->get() would also work as someone mentioned 

매김을 위해 당신이

$restaurants->comments()->paginate(15) 

대신

$restaurants->comments()->get()