为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel - 使用数据库功能改进的数据填充图表

Laravel - 使用数据库功能改进的数据填充图表

PHP
动漫人物 2023-11-04 19:58:40
我有一个管理仪表板,显示折线图,其中包含每月注册的用户数量。我正在从数据库获取数据,似乎一切正常,但功能相当大,我想知道是否有更优化和更有效的方法来获取和返回相同的数据?我将此函数分配给一个变量并将其传递到我的视图。// Get Monthly Registered Users This yearpublic 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;}它所做的就是获取每个月的注册用户数并将其分配给一个变量,然后返回包含每月用户数的数组。这可以改进吗?
查看完整描述

1 回答

?
人到中年有点甜

TA贡献1895条经验 获得超7个赞

您可以使用 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);

        }, range(1,12));

}


查看完整回答
反对 回复 2023-11-04
  • 1 回答
  • 0 关注
  • 106 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信