每个模型的Laravel极限渴望加载 [英] Laravel limit eager loading for each model

查看:55
本文介绍了每个模型的Laravel极限渴望加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用我们的用户模型,我们渴望加载对话和这些对话的消息.在每个对话中,我们都希望引导最后25条消息.因此,我们编写了以下查询.

With our User model we are eager loading conversations and messages of these conversations. Of each conversation, we would like to lead the last 25 messages. So we wrote the following query.

User::where('status', 3)->with(['conversations.messages' => function ($q) {
    $q->take(25)->orderBy('created_at', 'DESC');
}])->get();

但是,此函数总共仅返回25条消息(因此,每次会话均不返回).即使您有1000个用户,它也会加载邮件表中的最后25条消息,但不会每次用户会话加载最后25条消息.

However, this function only returns 25 messages in total (so not per conversation). Even if you have a 1000 users it will load the last 25 messages in the messages table but not the last 25 per conversation of a user.

Laravel雄辩的方法中是否有办法解决这个问题?

Is there a way to solve this within the Laravel Eloquent methodology?

推荐答案

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 Conversation extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

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

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

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

这篇关于每个模型的Laravel极限渴望加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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