代码之家  ›  专栏  ›  技术社区  ›  Marwelln

使用Eloquent统计所有分组行

  •  1
  • Marwelln  · 技术社区  · 8 年前

    我试图数一数所有分组的行,但不知道如何做到这一点,如果可能的话,用雄辩的。

    我的查询如下所示:

    SELECT COUNT(*) FROM (SELECT date FROM `reports` WHERE project_id = X GROUP BY `date`) as t1
    

    目前,我正在使用原始数据库查询:

    DB::select(DB::raw("SELECT COUNT(*) as total FROM (SELECT date FROM `" . (new Report)->getTable() . "` WHERE project_id = " . ((int) $this->project->id) . " GROUP BY `date`) as t1"))[0]->total
    

    有没有可能用雄辩的语言实现这一点,或者至少让PHP“调用”更漂亮?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Diogo Sgrillo    8 年前

    您可以使用 Query Builder :

    我会在这方面做一些事情(我认为您不需要该子查询):

    Report::where('project_id', $this->project->id)
        ->count(DB::raw('DISTINCT date'));