10
16

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 2020-01-16

Laravelでリレーション先で検索することがあったため備忘録。

例えば下記のようなモデルがあったとします。

User.php
class User extends Model
{
    public function project()
    {
        return $this->belongsTo('App\Project');
    }
}
Project.php
class Project extends Model
{
    public function organization()
    {
        return $this->belongsTo('App\Organization');
    }
}

※主キーはidとします。

リレーション先で検索

Userからリレーション先であるProjectのorganization_idで絞り込みたいとします。

  • whereHasを使用する場合
UserController.php
$Users = User::whereHas('project', function ($query) use ($request) {
    $query->where('organization_id', $request->organization_id);
})->get();

  • whereHasを使用しない場合
UserController.php
$Users = User::whereIn('project_id', function ($query) use ($request) {
    $query->from('projects')
        ->select('id')
        ->where('organization_id', $request->organization_id);
})->get();

リレーション先のリレーションで検索

Userからリレーション先であるProjectのリレーション先のOrganizationのnameで絞り込みたいとします。

  • whereHasを使用する場合
UserController.php
$Users = User::whereHas('project', function ($query) use ($request) {
    $query->whereHas('organization',  function ($query) use ($request) {
        $query->where('name', $request->organization_name);
    }
})->get();

  • whereHasを使用しない場合
UserController.php
$Users = User::whereIn('project_id', function ($query) use ($request) {
    $query->from('projects')
        ->select('id')
        ->whereIn('organization_id', function ($query) use ($request) {
            $query->from('organizations')
                ->select('id')
                ->where('name', $request->organization_name);
        });
})->get();

他により良い方法などありましたらご教示いただけますと幸いです。

10
16
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
10
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?