【问题标题】:Last 6 months number of users graph - Laravel过去 6 个月的用户数图 - Laravel
【发布时间】:2020-08-04 11:50:24
【问题描述】:

我想创建一个图表。使用下面的库。 https://charts.erik.cat/adding_datasets.html#database-eloquent-example-2

动态报告过去 6 个月用户数的查询

(with month rows
Sample:

January = 1,
February = 2,
March = 3
...)

我想要的输出是:

$user_count_chart = [
"2" => 30,
"3" => 41,
"4" => 50,
"5" => 62,
"6" => 72,
"7" => 150,
];

**

  • key:月份值
  • 值:用户数

**

Schema::create('users', function (Blueprint $table) {
  $table->bigIncrements('id');
  $table->string('email')->unique();
  $table->string('password');
  $table->dateTime('email_verified_at')->nullable();
  $table->rememberToken();
  $table->timestamps();
});

【问题讨论】:

    标签: sql laravel eloquent laravel-query-builder


    【解决方案1】:
    return User::groupBy('date')
            ->orderBy('date', 'desc')
            ->take(6)
            ->get([
                DB::raw('MONTH(created_at) as date'),
                DB::raw('count(id) as total')
            ])
            ->pluck('total', 'date');
    

    您可能需要小心的一件重要事情是,错过几个月。假设如果 3 月份没有任何用户,那么您的图表可能无法按预期工作。请检查this 的答案来解决这个“可能”的问题。

    【讨论】:

      【解决方案2】:

      可以使用 Laravel Collection 的groupBy() 函数。

      $user_count_chat = User::all()
          ->groupBy(function ($user) {
              return $user->created_at->month;
          })
          ->map(function ($group) {
              return $group->count();
          })
      

      编辑

      请注意,我认为月份数不够好,因为 2019-Jan 和 2020-Jan 的月份数相同,但它们不一样,我的建议是使用 'year-month'

      【讨论】:

      • 这个可能有性能问题,因为它在从数据库中获取所有用户后进行集合计算。
      • 我不这么认为,瓶坯集合计算与数据库分组几乎相同。这是我的 DBMS 完成的,这是由你完成的 :)
      • 不一样,获取100万用户在代码级别进行计算与获取9行汇总结果不同。
      • 是的,这无可争辩。
      猜你喜欢
      • 1970-01-01
      • 2020-08-15
      • 2020-04-02
      • 2023-03-28
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 2020-05-12
      • 1970-01-01
      相关资源
      最近更新 更多