【问题标题】:Laravel sum multiple withCount resultsLaravel 对多个 withCount 结果求和
【发布时间】:2022-01-01 05:24:51
【问题描述】:

我想按多个 whereCount 结果的总和排序。这是我的 whereCount

$q->withCount(['ordered', 'favorites']);

我想对这些ordered_count+favorites_count 求和并按此结果排序。我不太擅长使用 SQL,所以我需要一些帮助。如果使用 eloquent 查询生成器可以做到这一点,那就更好了。谢谢。

【问题讨论】:

  • 你能把orderedfavorites的关系代码贴出来

标签: mysql laravel eloquent


【解决方案1】:

您可以使用orderByRaw按总和排序:

$q->withCount(['ordered', 'favorites'])
->orderByRaw('(ordered_count + favorites_count) desc')
->get();

【讨论】:

  • 谢谢它的工作
猜你喜欢
  • 2021-07-17
  • 2020-05-29
  • 2017-06-18
  • 2014-07-09
  • 1970-01-01
  • 2017-04-07
  • 2020-04-17
  • 2019-08-06
  • 2014-06-09
相关资源
最近更新 更多