2016-08-14 88 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()