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?

【備忘録】QueryObjectパターン(laravelベース)

0
Posted at

QueryObjectとは

  • 複雑なデータベースクエリを専用のクラスに切り出して可読性・再利用性を高めるデザインパターン

メリット

  • 可読性・再利用性の向上
  • 複数の検索条件もオプションで簡単指定

仕様

  • クエリロジックをクラスの中にメソッドとして実装
  • EloquentのBuilderを返す

  • クラス
<?php

namespace App\Queries;

use App\Models\User;
use Illuminate\Database\Eloquent\Builder;

class ActivePaidUsersWithRecentProjectsQuery
{
    protected $relation;
    protected $options;

    public function __construct(Builder $relation = null, array $options = [])
    {
        $this->relation = $relation ?: User::query();
        $this->options = $options;
    }

    public function get(): \Illuminate\Database\Eloquent\Collection
    {
        return $this->query()->get();
    }

    protected function query(): Builder
    {
        $relation = $this->relation;
        $relation = $relation->where('status', 'active')
                             ->where('plan', '!=', 'free');

        if (!empty($this->options['recent_days'])) {
            $recentDays = $this->options['recent_days'];
            $relation = $relation->whereHas('projects', function (Builder $q) use ($recentDays) {
                $q->where('created_at', '>=', now()->subDays($recentDays));
            });
        }

        if (!empty($this->options['withRoles'])) {
            $relation = $relation->with('roles');
        }

        $relation = $relation->orderBy('created_at', 'desc');

        return $relation;
    }
}


  • 使い方
use App\Queries\ActivePaidUsersWithRecentProjectsQuery;

// 最近30日以内にプロジェクトを作った、アクティブで無料プランでないユーザーを取得
$users = (new ActivePaidUsersWithRecentProjectsQuery(null, ['recent_days' => 30]))->get();

// 役割情報も一緒に読み込む場合
$users = (new ActivePaidUsersWithRecentProjectsQuery(null, ['recent_days' => 30, 'withRoles' => true]))->get();
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?