[13.x] Fix `has()` and `withCount()` on self-referencing one-of-many relations
Existence queries on a self-referencing hasOne()->latestOfMany() or ofMany() relation return wrong results without any error. This covers has(), whereHas(), whereRelation(), withCount() and doesntHave():
class Comment extends Model
{
public function latestReply()
{
return $this->hasOne(Comment::class, 'parent_id')->latestOfMany();
}
}
Comment::has('latestReply')->get(); // empty, even for comments with replies
Comment::doesntHave('latestReply')->get(); // every comment
Eager loading works fine, only the existence queries break. For self relations the inner table is aliased to laravel_reserved_*, but the one-of-many join is merged before that happens, and its constraints use the already qualified foreign key. So the join compares against the outer comments table instead of the aliased one.
Same approach as #61818 for HasOneThrough: merge the one-of-many joins after the parent existence query has been built, and qualify the foreign key name in the join constraint so it picks up the alias. For non-self relations the generated SQL is unchanged.