概要
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の使い分け
以下の記事が分かりやすいと思います。