最近 6 个月的用户数图表 - Laravel
Last 6 months number of users graph - Laravel
我想创建一个图表。使用下面的库。
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,
];
**
- 键:月份值
- 值:用户数
**
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();
});
可以使用Laravel的groupBy()
功能Collection。
$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'
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 月没有任何用户,那么您的图表可能无法按预期工作。请检查 答案以解决此 "possible" 问题。
我想创建一个图表。使用下面的库。 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,
];
**
- 键:月份值
- 值:用户数
**
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();
});
可以使用Laravel的groupBy()
功能Collection。
$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'
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 月没有任何用户,那么您的图表可能无法按预期工作。请检查