mysql - Count & GroupBy 函数 Laravel

标签 mysql sql laravel count eloquent

我正在使用 Laravel 为管理员仪表板构建一些分析统计图。我玩得很开心。尽管我在理解如何利用 SQL 查询和 GroupBy 函数来实现一些东西时遇到了一些困难。

最终目标:检索创建的用户计数以及他们注册的那一周groupBy

到目前为止,我正在使用这个:

DB::table("users")
   ->select(DB::raw("COUNT(*) as count"))
   ->orderBy("created_at")
   ->groupBy(function ($query)
     {
       return \Carbon\Carbon::parse($query->created_at)->format("W");
     })
   ->get();

我在 Tinker 中遇到一个错误(这是我目前进行大部分测试的地方,它是这样的:

PHP warning:  strtolower() expects parameter 1 to be string,  object given in 
/Users/Ian/sites/bangerz-army/vendor/laravel/framework/src/Illuminate/Database/Grammar.php on line 58

我在 PHP 中得到了一个类似的查询,但出于性能原因,我更愿意将尽可能多的数学运算保留在 SQL 中。

/拉维尔 5.5

最佳答案

尝试在你的组中使用 DB::raw()

DB::table("users")
   ->select(DB::raw("COUNT(*) as count, WEEK(created_at)"))
   ->orderBy(DB::raw('WEEK(created_at)'))
   ->groupBy(DB::raw('WEEK(created_at)'))
   ->get();

关于mysql - Count & GroupBy 函数 Laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46595925/

相关文章:

laravel - 如何防止使用 phpunit 触发模型事件?

php - Laravel UTF-8 到数据库

mysql - 如何在 MySQL 中自连接聚合函数的结果?

php - 使用 PHP 和 MYSQL 制作最喜欢的工作列表

mysql - 组合主键 VS。 MySQL 中的辅助键

php - Laravel 查询生成器 : MySQL 'LIKE' inside a multiple where conditioned query

php - 在 Laravel 5.5 中使用 Carbon 来比较 2 个日期

php - 尝试为用户显示@mentions,但我的查询出现错误

c# - SQL 随机化行和列

mysql - 创建数据库,什么字符集适合我的目的