Skip to content

[13.x] Fix has() and withCount() on self-referencing one-of-many relations - #62009

Merged
taylorotwell merged 2 commits into
laravel:13.xfrom
sumaiazaman:13.x-fix-self-referencing-one-of-many-existence-queries
Oct 14, 2026
Merged

taylorotwell merged 2 commits into
laravel:13.xfrom
sumaiazaman:13.x-fix-self-referencing-one-of-many-existence-queries

Conversation

@sumaiazaman

Copy link
Copy Markdown
Contributor

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.

@taylorotwell
taylorotwell merged commit a0d6db3 into laravel:13.x Oct 14, 2026
64 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants