Thanks for the response @snapey!
Here is an example set of data demonstrating, but regardless I don't think it changes the core question.
Users
| id | role_id |
| ------------ |
| 1 | 45 |
| 2 | 46 |
Roles
| id | role_id |
| ------------ |
| 1 | 45 |
| 2 | 45 |
| 3 | 46 |
| 4 | 46 |
Our data is not quite structured like this, but I was attempting to simplify - obviously I failed. The core question, however, relates to what Laravel is doing here:
https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php#L84
and here:
https://github.com/laravel/framework/blob/7.x/src/Illuminate/Database/Eloquent/Relations/Relation.php#L80
Inside of a whereHas block Laravel is removing the initial constraints on all relationship instances (the $constraints variable is static). I'm curious what I can do to prevent it from happening on certain relationships (like my calls to auth()->user()->roles within the whereHas).
Changing my roles() relationship to look like this fixes it within the whereHas block, but then adds a redundant constraint for all uses outside of the whereHas block.
public function roles()
{
return $this->hasMany(Role::class, 'role_id', 'role_id')->where('role_id', $this->role_id);
}
Thanks again for the response, let me know if I can clarify further.