简体   繁体   English

从多个相关记录中获取一组相关记录laravel?

[英]Get a set of related records from multiple related records laravel?

I have users that have multiple restaurants , then each restaurant has comments . 我有多个restaurants users ,然后每个restaurant都有comments

So when a user logs in, I would like to show a list of all the comments from restaurants related to the user. 因此,当user登录时,我想显示restaurants与该用户相关的所有comments的列表。

I am using laravel 5.1 我正在使用laravel 5.1

What I have so far is: 到目前为止,我有:

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

I get a BadMethodCallException , I think I am not doing this the laravel way. 我收到BadMethodCallException ,我想我不是以laravel的方式这样做。

Have u tried Have Many Through? 您是否尝试过许多?
In User model public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); } 在用户模型中, public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); } public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); } And in controller u easily to access comments $comments = $user->user_posts(); public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); } 并且在控制器ü容易访问评论 $comments = $user->user_posts(); More details here: https://laravel.com/docs/5.1/eloquent-relationships#has-many-through 此处有更多详细信息: https : //laravel.com/docs/5.1/eloquent-relationships#has-many-through

I have just found the answer, to use merge the dataset needs to be a collection . 我刚刚找到了答案,要使用merge ,数据集需要是一个collection

So to create the collection you need to use: ->get(); 因此,创建集合需要使用: ->get();

In my example: 在我的示例中:

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

Note: the paginate function has to go, it is nota method of a laravel Collection 注意:必须启用分页功能,这不是laravel Collection方法

You were almost correct, you should have done 你几乎是正确的,你应该做的

$restaurant->comments
// gives you objects

instead of 代替

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

as for pagination you can do 至于分页,你可以做

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

instead of 代替

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM