如何解决Laravel-使用来自数据库功能改进的数据填充图表
我有一个管理仪表板,显示折线图,其中包含每月注册的用户数。 我正在从数据库中获取数据,并且看起来一切正常,但是该功能相当大,我想知道是否有一种更优化,更有效的方式来获取和返回相同数据?
我正在将此函数分配给变量并将其传递给我的视图。
// Get Monthly Registered Users This year
public function monthlyRegisteredUsers()
{
$janUsers = User::whereMonth('created_at',1)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$febUsers = User::whereMonth('created_at',2)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$marUsers = User::whereMonth('created_at',3)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$aprUsers = User::whereMonth('created_at',4)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$mayUsers = User::whereMonth('created_at',5)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$junUsers = User::whereMonth('created_at',6)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$julUsers = User::whereMonth('created_at',7)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$augUsers = User::whereMonth('created_at',8)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$sepUsers = User::whereMonth('created_at',9)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$octUsers = User::whereMonth('created_at',10)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$novUsers = User::whereMonth('created_at',11)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$decUsers = User::whereMonth('created_at',12)->whereYear('created_at',Carbon::now()->format('Y'))->count();
$data = [$janUsers,$febUsers,$marUsers,$aprUsers,$mayUsers,$junUsers,$julUsers,$augUsers,$sepUsers,$octUsers,$novUsers,$decUsers ];
return $data;
}
它所做的只是获取每月的注册用户数并将其分配给变量,然后返回包含每月用户数的数组。 这可以改善吗?
非常感谢
解决方法
您可以使用array_map和range使此代码更短:
public function monthlyRegisteredUsers()
{
return array_map(function($month){
return User::whereMonth('created_at',$month)->whereYear('created_at',Carbon::now()->format('Y'))->count();
},range(1,12))
}
我认为您可以使用group by来运行一个查询,让我通过一个更好的查询来更新答案。
public function monthlyRegisteredUsers()
{
$counts = User::select(DB::raw('MONTH(created_at) month,count(*) as count'))
->whereYear('created_at',Carbon::now()->format('Y'))
->groupBy(DB::raw('MONTH(created_at)'))
->pluck('count','month')
->toArray();
return array_map(function($month) use ($counts){
return Arr::get($counts,$month,0);
},12));
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。