【问题标题】:How to create an Laravel Eloquent query that return more than one aggregate?如何创建一个返回多个聚合的 Laravel Eloquent 查询?
【发布时间】:2021-04-16 21:37:55
【问题描述】:

我是 Laravel 和 Eloquent 新手。

我正在尝试将旧应用程序移植到 Laravel。

现在我想将以下 RAW SQL 查询转换为 Eloquent:

  SELECT COUNT(county_id) AS qt_counties,
      SUM(population) AS total_population
    FROM population_county
    WHERE population >= 5000
      AND population < 10000
      AND year = "2020"
    GROUP BY year

我面临的问题是我不知道如何编写一个同时返回两个聚合的 Eloquent 查询。

我试过了

  $qt = PopulationCounty::where('year', $year)
    ->where('population', '>=', $min)
    ->where('population', '<', $max)
    ->distinct('county_id')
    ->sum('population');

但它只返回一个聚合。

它可以作为 Eloquent 查询完成,还是我应该在 Eloquent 中使用某种“RAW 查询”支持?

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    看起来您可以使用 SelectRaw 来返回多个聚合:

    这可能会有所帮助:

    https://laravel.io/forum/06-17-2014-multiple-aggregates-in-one-query

    jarektkaczyk 的回复应该会帮助您顺利上路。

    他基本上是说你可以在更原始的状态下构建查询,而不是试图让雄辩的人做你想做的事:)

    【讨论】:

      【解决方案2】:
      $qt = PopulationCounty::selectRaw('COUNT(county_id) AS qt_counties, SUM(population) AS total_population')
              ->where('year', $year)
              ->where('population', '>=', $min)
              ->where('population', '<', $max)
              ->groupBy('year');
      

      【讨论】:

      • 请在您的回答中添加一些描述
      猜你喜欢
      • 2013-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2022-01-10
      • 1970-01-01
      相关资源
      最近更新 更多