Laravel limit eager loading for each model

拈花ヽ惹草 提交于 2020-12-26 04:26:21

问题


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?


回答1:


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 \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

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

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



来源:https://stackoverflow.com/questions/53837614/laravel-limit-eager-loading-for-each-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!