使用我们的用户模型,我们渴望加载对话和这些对话的消息.在每个对话中,我们都希望引导最后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极限渴望加载
发布评论