gpt4 book ai didi

laravel - 如何在 Eloquent 中使用 join 和 sum?

转载 作者:行者123 更新时间:2023-12-02 04:31:37 26 4
gpt4 key购买 nike

我需要选择我网站上投票最多的文章。现在,我有这个功能来处理小错误,但我把它写成原始 SQL 查询。错误就像是,我通过原始 sql 查询获得了大多数投票的文章,然后使用 Eloquent 的 whereIn 方法和 id,但它似乎以随机顺序返回响应。此外,它会破坏 Eloquent 的 ->isEmpty() 方法,我在我的观点中大量使用了该方法。

长话短说,我厌倦了在这个小脚本上尝试编写原始查询并解决大量错误(或副作用)的写作。我想把它带到 Eloquent(有关系)并完成它。

我当前的数据库架构:

articles
--id

votes
--id
--user
--article_id
--vote
  1. Articles.idvotes.article_idhasMany相关(一篇文章可能有很多票)
  2. vote 列只能包含 1-1 值。
  3. 我需要运行一个查询来选择前 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com