0
1

More than 1 year has passed since last update.

【Laravel】EloquentCollectionにてネスト先カラムをGroupByする

Posted at

はじめに

そもそも1カラムに複数値を持たせるのはどうかという点は置いといておいて、、、。
何らかしらのレスポンスデータをログとしてそのまま格納したい場合などあると思います。
こちら調べてもあまり記事がなく、もしかしたらやりたい人がいるかな~と思いメモとして記事に残しておきます。

要件

Jsonがそのまま入ったカラムにて、Jsonのキーでグルーピングしたい

結論

// ドット「.」でつなげる
$collection->gropuBy('xxx.xxx');

検証内容

テーブル構成

migration.php
Schema::create('conversions', function (Blueprint $table) {
    $table->id();
    $table->json('meta');
    $table->timestamps();
});

データ

id meta created_at updated_at
1 {"gender": "male", "browser": "chrome", "language": "jp"} 2022-05-14 02:56:45 2022-05-14 02:56:45
2 {"gender": "female", "browser": "edge", "language": "en"} 2022-05-14 02:56:45 2022-05-14 02:56:45
3 {"gender": "male", "browser": "safari", "language": "en"} 2022-05-14 02:56:45 2022-05-14 02:56:45

モデル

Convesion.php
<?php

declare(strict_types=1);

namespace App\Models

class Conversion extends BaseModel
{
    protected $fillable = [
        'meta'
    ];

    protected $dates = [
        'updated_at',
        'created_at',
    ];

    protected $casts = [
        'meta' => 'json',
    ];
}

コード

$_conversions = Conversion::get();
$conversions = $_conversions->groupBy('meta.gender');

// 出力結果(ログ抜粋)
Illuminate\Database\Eloquent\Collection Object
    [male] => Illuminate\Database\Eloquent\Collection Object (
        [items:protected] => Array (
            [0] => App\Models\Conversion Object (
                [attributes:protected] =>
                Array ( [id] => 1 [meta] => {"gender": "male", "browser": "chrome", "language": "jp"} [created_at] => 2022-05-14 02:56:45 [updated_at] => 2022-05-14 02:56:45 )
            )
            [1] => App\Models\Conversion Object (
                [attributes:protected] =>
                Array ( [id] => 3 [meta] => {"gender": "male", "browser": "safari", "language": "en"} [created_at] => 2022-05-14 02:58:34 [updated_at] => 2022-05-14 02:58:34 )
            )
        )
    )
    [female] => Illuminate\Database\Eloquent\Collection Object ( [
        [items:protected] => Array (
            [0] => App\Models\Conversion Object (
                [attributes:protected] =>
                Array ( [id] => 2 [meta] => {"gender": "female", "browser": "edge", "language": "en"} [created_at] => 2022-05-14 02:58:09 [updated_at] => 2022-05-14 02:58:09 )
            )
        )
    )

EloquentModelが保持された状態でグループ化される

最後に

最後まで記事を見ていただきありがとうございます。
ご意見等ありましたらよろしくお願いします。

0
1
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
1