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

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

问题描述

大家好,我使用的是 Laravel 5.6 我在数据库帖子、评论和回复中有三个表以及三个模型帖子、评论、回复

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-急切限制

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

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

class Post extends Model {
    use StaudenmeirEloquentEagerLimitHasEagerLimit;
}

class Comment extends Model {
    use StaudenmeirEloquentEagerLimitHasEagerLimit;
}

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

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

回复也是一样.

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

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