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

标签 laravel eloquent

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

相关文章:

php - 拉拉维尔背包。 1-1(一对一)关系

laravel - 调用未定义的方法 Illuminate\Database\Eloquent\Relations\BelongsTo::save()

php - Laravel 5 - link_to_route() 方法通过在末尾添加 "?"使我的路由参数变为查询字符串

laravel - 处理Laravel中找不到的数据

php - Laravel:在 View 中使用模型关系是一个好的实践吗?

php - 当有数量和价格时,在 eloquent laravel 中使用 sum

mysql - 如何在Laravel 5中处理BIT数据类型?

laravel - 409 冲突错误仅在 wifi 上仅在注册期间

VerifyCsrfToken.php 第 68 行中的 Laravel 5.4 TokenMismatchException

php - 登录成功后重定向