我需要选择我网站上投票最多的文章。现在,我有这个功能来处理小错误,但我把它写成原始 SQL 查询。错误就像是,我通过原始 sql 查询获得了大多数投票的文章,然后使用 Eloquent 的 whereIn
方法和 id,但它似乎以随机顺序返回响应。此外,它会破坏 Eloquent 的 ->isEmpty()
方法,我在我的观点中大量使用了该方法。
长话短说,我厌倦了在这个小脚本上尝试编写原始查询并解决大量错误(或副作用)的写作。我想把它带到 Eloquent(有关系)并完成它。
我当前的数据库架构:
articles
--id
votes
--id
--user
--article_id
--vote
Articles.id
和votes.article_id
与hasMany
相关(一篇文章可能有很多票)vote
列只能包含1
和-1
值。- 我需要运行一个查询来选择前 10 篇获得最多好评的文章。在原始 sql 中,它是
group by votes.article_id order by sum(votes.vote)
(我们不只选择正面投票,而是选择 votes.vote 列的 SUM。)
例如:
articles.id
1
2
votes.id votes.user votes.article_id votes_vote
1 User1 1 1
2 User2 1 1
3 User3 1 -1 (this is negative vote)
4 User1 2 1
5 User2 2 1
输出应该是:
Article 2 has (2) vote rating. // 1 + 1
Article 1 has (1) vote rating // 1 + 1 - 1
我该怎么做?
附言。如果你愿意,你可以使用 Eloquent 的 DB::raw
方法,只要它使用 Eloquent。
最佳答案
瞧
Article::leftJoin(
DB::raw('(SELECT article_id, SUM(vote) AS votes FROM votes GROUP BY post_id) as v'),
'v.post_id', '=', 'posts.id'
)->orderBy('votes', 'desc')->take(10)->get();
关于laravel - 如何在 Eloquent 中使用 join 和 sum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22948835/