我有评论列表API与Pagination在laravel,我想要一个评论重播数组与每个评论,但只有最后3个评论重播。
public function CommentReplay(){
return $this->hasMany('AppPostCommentReplies','comment_id','id')->orderBy('id','DESC');
}
And Query I have use
PostComments::select('post_comments.*')->with(['users','CommentReplay'=> function ($query) {
$query->select('post_comment_replies.*')
->orderBy('id','DESC')->take(3);
}])->orderBy('id','DESC')->paginate(10);
在这个,我一直只得到最后3个评论的所有CommentReplay数组。我一直没有收到每个评论的最后3个回复。我希望每个评论能有3个回复。
谁都可以帮我。
谢谢!
你可以使用trait: HasEagerLimit:
你可以安装它:
composer require staudenmeir/eloquent-eager-limit:"^1.0"
然后在你的模型中:
class PostComments extends Model {
use StaudenmeirEloquentEagerLimitHasEagerLimit;
public function CommentReplay(){
return $this->hasMany('AppCommentReplay');
}
public function limitCommentReplay(){
return $this->hasMany('AppCommentReplay')->latest()->limit(3);
}
}
以及PostCommentReplies模型:
class CommentReplay extends Model {
use StaudenmeirEloquentEagerLimitHasEagerLimit;
}
now:当你加载你的关系…它应该返回您想要的结果:
PostComments::select('post_comments.*')->with(['users','limitCommentReplay'])->orderBy('id','DESC')->paginate(10);