问题
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