如何使用嵌套模型加载Laravel并限制嵌套模型? [英] How to load Laravel with nested models and limit the nested models?

查看:158
本文介绍了如何使用嵌套模型加载Laravel并限制嵌套模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用Laravel 5.6,我在数据库中有三个表posts,comments和replies和三个模型Post,Comment,Reply

Hello guys I am using Laravel 5.6 I have three tables in the database posts,comments and replies and three models Post , Comment , Reply

这种关系如下:一个帖子有很多评论,而一个评论有很多回复.我创建了一条路线,当点击时将返回一些数据;但是,我希望此数据以特定的方式阅读此示例:

the relations are as follow one post has many comments and one comment has many replies. I created a route that when hit will return some data ;however, I want this data to be in a specific way read this example:

让我们说我在数据库中有6条帖子,每条帖子有6条评论,每条评论都有6条回复,我只想返回前3条帖子,以及每条帖子的前3条评论,以及每条评论的前3条回复

Lets say I have 6 posts in my database and each post has 6 comments also each comment has 6 replies I want to return only the first 3 posts along with the first 3 comments for each post also the first 3 replies for each comment

//this is a function inside a controller 
//and for sure I have make sure to make use of the models namespaces 

public function test(){
    $posts = Post::with(['comments' => function($data){
        return $data->take(3);
    },
    'comments.replies' => function($data){
        return $data->take(3);
    }])->paginate(3);

    //returning the posts
    return $posts
}

以这种方式工作,它返回前3条帖子,并且仅返回第一条帖子的前3条评论和前3条回复,但对于其他帖子,我只得到空的评论键,因此没有任何回复

This way is working it returns the first 3 post and it returns the first 3 comments and first 3 replies only for the first post but for other posts I only get an empty key of comments so there is no replies as a result

希望您能收到我的问题,请帮忙 抱歉,有个大问题 预先感谢.

hope you get my question please help sorry for big question Thanks in advance.

推荐答案

Laravel中对此没有本地支持.

There is no native support for this in Laravel.

我为此创建了一个程序包: https://github.com/staudenmeir/eloquent-渴望极限

I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit

在父模型和相关模型中都使用HasEagerLimit特征.

Use the HasEagerLimit trait in both the parent and the related model.

class Post extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Comment extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

然后,您可以将->take(3)应用于您的关系.

Then you can apply ->take(3) to your relationship.

答复也一样.

这篇关于如何使用嵌套模型加载Laravel并限制嵌套模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆