0
0

Laravel Eloquentで親テーブル小テーブル共に検索対象にする方法

Posted at

概要

Laravel Eloquentにおいて、親子テーブル両方を検索対象にする方法について、この記事では記載する。

解決方法

orWhereHas を使って検索対象に含めれば、解決することが出来る。

App\Models\Player.php

public function team(): BelongsTo
{
    return $this->belongsTo(Team::class);
}

static public function findBySearch(string $input)
{
    $players = Player::makeBuilder($input)->get()->load('team');
    return $players;
}

static private function makeBuilder(string $input)
{
    return Player::where('name', 'LIKE', '%' . $input . '%')
        ->orWhere('age', 'LIKE', '%' . $input . '%')
        ->orWhere('position', 'LIKE', '%' . $input . '%')
        ->orWhereHas('team', function ($query) use ($input) {
            $query->where('name', 'like', '%' . $input . '%')
                ->orWhere('area', 'like', '%' . $input . '%');
        });
}

補足

withとloadの使い分け

以下の記事が分かりやすいと思います。

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