2016-08-14 101 views
-1

我有users有多個restaurants,那麼每個restaurantcomments從多個相關記錄laravel中獲取一組相關記錄?

因此,當user登錄時,我想顯示與用戶相關的所有commentsrestaurants相關的列表。

我使用laravel 5.1

我有什麼到目前爲止是:

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

我得到一個BadMethodCallException,我覺得我沒有做這樣的laravel方式。

回答

0

我剛剛找到答案,要使用merge,數據集需要是collection

所以創建你需要使用集合:->get();

在我的例子:

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

注:PAGINATE功能已去,這是一個laravel的諾塔方法Collection

+1

你仍然可以做分頁,替換 - >獲得()與 - > PAGINATE(15) –

0

你幾乎是正確的,你應該做的

$restaurant->comments 
// gives you objects 

而不是

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

爲分頁,你可以做

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

,而不是

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