0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Laravelクエリビルダ】曜日別にグループ化して集計する方法

Last updated at Posted at 2021-07-12

Laravelのクエリビルダで曜日別にグループ化して集計する方法を解説します。

バージョンは6系です。

ブログでLaravel初学者に向けた以下のような記事も以下のような記事も書いています。

 ゴール

曜日 合計
200
300
500

準備

postsテーブルに以下のデータを用意。

post_id amount created_at
1 100 2021-06-01 12:23:07
2 200 2021-06-15 15:23:23
3 300 2021-06-30 16:21:12
4 400 2021-07-21 19:23:32
5 200 2021-07-27 15:04:56

ここから、created_atの曜日をグループ化させて、amountの合計値を算出する。

ちなみに 5つの日付は火曜か水曜になっています。
なので完成は、以下となります。

曜日 合計
合計値
合計値

考え方

曜日でグループ化させるために、WEEKDAY関数を使う。
ビューで表示する際に、曜日の配列を用意する。
foreachと曜日の配列をもとに曜日を表示させる。

WEEKDAY関数の他にDAYOFWEEKがあります。違いは、WEEKDAYは月曜始まりで、DAYOFWEEKは日曜始まりな点です。

簡単に言えば、WEEKDAY関数は日付を月曜なら0,火曜なら1を返します。
DAYOFWEEKなら日曜なら0,月曜なら1を返します。

サンプルコード

モデル(Post.php)

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;←忘れずに記載する

class Post extends Model
{
    public function getAmountByHour()
    {
      return DB::table('posts')
              ->selectRaw('WEEKDAY(created_at) AS week')
              ->selectRaw('SUM(amount) AS total_amt')
              ->groupBy('week')
              ->get();
    }
}

selectRawはselect(DB::raw)の省略形。
WEEKDAY関数を使って曜日をグループ化させます。

WEEKDAY(created_at)で日付が対応する曜日となって返します。

例えば、2021-06-01は火曜日なので、->selectRaw('WEEKDAY(created_at) AS week')は1を返します。

WEEKDAY関数やSUM,COUNT関数などを使う場合は、DB::rawが必要です。

SUM(amount)でamountの合計値を出しています。

最後にgroupBy('week')でグループ化しています。
AS weekWEEKDAY(created_at)に別名をつけています。

コントローラー(PostController.php)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;←バージョン8系なら use App\Models\Post;

class PostController extends Controller
{
    public function index()
    {
        $this->posts = new Post();

        $results = $this->posts->getAmountByHour();

        return view('posts.index', compact(
            'results',
        ));
    }
}

ビュー(index.blade.php)

<table>
    <thead>
      <tr>
        <th>曜日</th>
        <th>合計</th>
      </tr>
    </thead>
    <tbody>
    @foreach ($results as $result)
      @php
        $week = [
                '月', //0
                '火', //1
                '水', //2
                '木', //3
                '金', //4
                '土', //5
                '日', //6
                ];
        @endphp
      <tr>
        <td>{{ $week[$result->week] }}</td>
        <td>{{ $result->total_amt }}</td>
      </tr>
    @endforeach
    </tbody>
</table>

ビューで曜日の配列を作ります。WEEKDAY関数を使っているので、
0は月曜、1は火曜...となります。配列で対応させるように書いていきましょう。

$result->weekには、1とか2とか数字が戻り値となります。
なので、$week[0]は月曜、$week[1]は火曜になるってわけですね。

ブログでLaravel初学者に向けた以下のような記事も以下のような記事も書いています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?