每个模型的Laravel极限渴望加载

编程入门 行业动态 更新时间:2024-10-27 08:24:57
本文介绍了每个模型的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.

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

I created a package for it: github/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极限渴望加载

本文发布于:2023-08-04 06:04:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1293630.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:模型   加载   极限   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!