【问题标题】:How can I use join and sum with Eloquent?如何在 Eloquent 中使用 join 和 sum?
【发布时间】:2014-04-09 06:22:13
【问题描述】:

我需要在我的网站上选择投票最多的文章。现在,我有这个功能可以处理一些小错误,但我把它写成一个原始的 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。

【问题讨论】:

  • 如果它更简洁可能是一个更好的问题!

标签: laravel eloquent


【解决方案1】:

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();

【讨论】:

  • 非常感谢。进行虚拟拥抱。
猜你喜欢
  • 2019-07-17
  • 2016-09-28
  • 1970-01-01
  • 2020-04-28
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 2010-10-06
相关资源
最近更新 更多