Laravel 限制每个模型的预加载 [英] Laravel limit eager loading for each model

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

问题描述

通过我们的 User 模型,我们渴望加载对话和这些对话的消息.在每个对话中,我们希望引导最后 25 条消息.所以我们写了下面的查询.

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

然而,这个函数总共只返回 25 条消息(所以不是每个对话).即使您有 1000 个用户,它也会加载消息表中的最后 25 条消息,但不会加载用户每个会话的最后 25 条消息.

有没有办法在 Laravel Eloquent 方法中解决这个问题?

解决方案

Laravel 中没有对此的原生支持.

我为它创建了一个包:https://github.com/staudenmeir/eloquent-急切限制

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

class Conversation extends Model {使用 StaudenmeirEloquentEagerLimitHasEagerLimit;}类消息扩展模型{使用 StaudenmeirEloquentEagerLimitHasEagerLimit;}

然后简单地将 ->take(25) 调用链接到您的急切加载查询(您似乎已经这样做了).

您甚至可以使用 ->offset(...)->skip(...)(有关详细信息,请参阅存储库自述文件).

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();

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.

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

解决方案

There is no native support for this in Laravel.

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

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

class Conversation extends Model {
    use StaudenmeirEloquentEagerLimitHasEagerLimit;
}

class Message extends Model {
    use StaudenmeirEloquentEagerLimitHasEagerLimit;
}

Then simply chain ->take(25) call to your eager-load query (which seems you already do).

You could even use ->offset(...) and ->skip(...) (see repository readme for details).

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

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