【发布时间】:2019-12-02 17:44:33
【问题描述】:
在我的网站上,我有提交,提交可以有 cmets。
评论可以有赞成票和反对票,从而导致评论的总“得分”。
在本例中,在将 cmets 传递给视图之前,我按分数对它们进行排序。
$comments = Comment::where('submission_id', $submission->id)->where('parent_id', NULL)->get();
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
});
这很好用。评论的分数越高,它的排序就越高。
但是,我想对这些结果进行分页。
如果我使用->paginate(10) 而不是get(),则以下sortByDesc 只会对这10 个结果进行排序。
所以从逻辑上讲,我想在sortByDesc 之后添加分页器,如下所示:
$comments = $comments->sortByDesc(function($comment){
return count($comment['upvotes']) - count($comment['downvotes']);
})->paginate(10);
但是这会返回错误:
方法 Illuminate\Database\Eloquent\Collection::paginate 没有 存在。
正如预期的那样。
我的问题是,在这种情况下使用 paginate 的替代方法是什么?
编辑:
尝试@party-ring 的响应(并切换双引号和单引号)时,出现以下错误:
SQLSTATE[42000]:语法错误或访问冲突:1064 你有一个 SQL 语法错误;检查与您对应的手册 MariaDB 服务器版本,用于在 '["upvotes"]) 附近使用正确的语法 - count($comment["downvotes"]) desc limit 10 offset 0' at line 1 (SQL: select * from
commentswheresubmission_id= 1 andparent_idis 按计数为空($comment["upvotes"]) - count($comment["downvotes"]) desc limit 10 offset 0)
【问题讨论】:
标签: laravel