Closed hafezdivandari closed 2 years ago
Hi @hafezdivandari,
I believe every Laravel Relation classes that use getRelationCountHash() to generate alias for self-related relation also have this issue, am I right?
Yes, that's right. I recommend that you use qualifyColumn()
to get the correct table name automatically:
\App\Models\User::whereHas('teammates', function (Builder $query) {
$query->where($query->qualifyColumn('id'), 2);
})->get();
Does that work for you?
Hi @staudenmeir thank you, that works but why not sending a PR on Laravel? it is obvious that using whereHas
on self-related relations doesn't work.
We already know the condition, we can only qualify the column when it's self related relation and is not already qualified (i.e. it doesn't contain '.') right? so it won't be a breaking change.
I know they apply query constraints on this line. Maybe I should right another callScope
for this, I'm not sure how to do it.
I'm really sorry to bother you, I know it is not directly related to this repo but you are expert on Laravel relations, even if I figure out how to solve this, such PRs doesn't get merge easily without support. Just close this issue if you are not interested.
We already know the condition, we can only qualify the column when it's self related relation and is not already qualified (i.e. it doesn't contain '.') right? so it won't be a breaking change.
That's not possible because we don't know which table an unqualified constraint is referring to. In your case, it could refer to the teams
table and we would break the query by automatically qualifying the column.
@staudenmeir I don't think so, because qualifyColumn
does qualify the given column if it doesn't contain .
, If I want to refer to teams
table I can simply do:
\App\Models\User::whereHas('teammates', function (Builder $query) {
$query->where($query->qualifyColumn('teams.id'), 2); //would be as same as $query->where('teams.id', 2);
})->get();
if I want to refer to teams table I can simply do:
You can do that when you write new code, but changing whereHas()
would break existing queries where the column isn't qualified.
I have
User
andUserTeam
models and this self-related relation onUser
model:It works fine and I can get
teammates
of a user, but when using onwhereHas
to get users that have e.g userid = 2
as their teammates it doesn't work:because column
'id'
in where clause is ambiguous. we can't useusers.id
either, here is the SQL:I think we have 2 way to solve this:
has
/whereHas
:laravel_reserved_0
:I believe every Laravel Relation classes that use
getRelationCountHash()
to generate alias for self-related relation also have this issue, am I right? (related to laravel/framework#42075)Meanwhile thank you so much for this useful and well-written package.