猿问

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;

}

它所做的就是获取每个月的注册用户数并将其分配给一个变量,然后返回包含每月用户数的数组。这可以改进吗?


动漫人物
浏览 109回答 1
1回答

人到中年有点甜

您可以使用 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));}
随时随地看视频慕课网APP
我要回答