Where relationship column equals?
Asked Answered
H

2

35

I am trying to grab all records where Player's relationship called stats() has a column value of something. I would usually do ::where('column_name' 'column_value') for the players table, but how can I get ::where the relationship table's column equals to something?

Player::where('column_name', 'column_value')->get();

But I want to check a column in the relationships table?

public function roleplay()
{
    return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id', 'id');
}
Humphreys answered 29/3, 2017 at 23:20 Comment(1)
Check this section in Laravel's documentation: laravel.com/docs/5.4/…Favors
D
96

This will filter Player based on a related table

Player::whereHas('roleplay', function($q){
   $q->where('column_name', 'value');
})->get();
Devote answered 29/3, 2017 at 23:31 Comment(1)
Thanks, this was the ticket!Diffident
L
24

Laravel 8^ : doc Relationship Existence Queries

Product::with('categoreys')->whereRelation('categoreys', 'status', '0')
                                            ->get();
Lashawna answered 20/2, 2022 at 22:32 Comment(3)
That's just a shortened way of writing of @oseintow's answerBrittan
Please note that by using with two database queries will be executed. The accepted answer that uses whereHas will result in a single query.Veronaveronese
It's a good (or at least 'clean') way for nested relationships. Thanks.Bourque

© 2022 - 2024 — McMap. All rights reserved.