[13.x] Fix existence and aggregate queries on self-referencing one-of-many relations

Merged
XU
17d ago
+117-7

Self-referencing one-of-many relations still fail in has(), whereHas(), withCount(), withExists() and the other relation aggregates in a few cases.

With ofMany() on a column:

public function topReply()
{
    return $this->hasOne(Comment::class, 'parent_id')->ofMany('score', 'max');
}

Comment::has('topReply')->get(); // Unknown column 'laravel_reserved_0.score'

With latestOfMany() when the model uses SoftDeletes, it fails on laravel_reserved_0.deleted_at.

With morphOne(...)->latestOfMany() there's no error, but has() returns no comments even though eager loading finds the replies.

In all three the one-of-many join ends up pointing at the wrong table: the inner subqueries get the alias, or the outer join doesn't.