diff --git a/src/RelationJoinQuery.php b/src/RelationJoinQuery.php index ad4a087..dfcd536 100644 --- a/src/RelationJoinQuery.php +++ b/src/RelationJoinQuery.php @@ -261,8 +261,14 @@ protected static function hasOneOrManyThrough(Relation $relation, Builder $query */ protected static function morphOneOrMany(Relation $relation, Builder $query, Builder $parentQuery, string $type = 'inner', string $alias = null) { + if (! is_null($alias) && $alias != $relation->getRelated()->getTable()) { + $query->from($relation->getRelated()->getTable() . ' as ' . $alias); + + $relation->getRelated()->setTable($alias); + } + return static::hasOneOrMany($relation, $query, $parentQuery, $type, $alias)->where( - $relation->getQualifiedMorphType(), '=', $relation->getMorphClass() + $relation->getRelated()->qualifyColumn($relation->getMorphType()), '=', $relation->getMorphClass() ); } diff --git a/tests/Unit/MorphOneTest.php b/tests/Unit/MorphOneTest.php index 6b72782..bbd5bb7 100644 --- a/tests/Unit/MorphOneTest.php +++ b/tests/Unit/MorphOneTest.php @@ -25,12 +25,26 @@ public function basic(Closure $query, string $builderClass) * @test * @dataProvider queryDataProvider */ - public function alias(Closure $query, string $builderClass) + public function alias_not_nested(Closure $query, string $builderClass) { $builder = $query(new EloquentPostModelStub) - ->joinRelation('image'); + ->joinRelation('image as photos'); - $this->assertEquals('select * from "posts" inner join "images" on "images"."imageable_id" = "posts"."id" and "images"."imageable_type" = ?', $builder->toSql()); + $this->assertEquals('select * from "posts" inner join "images" as "photos" on "photos"."imageable_id" = "posts"."id" and "photos"."imageable_type" = ?', $builder->toSql()); + $this->assertEquals([0 => EloquentPostModelStub::class], $builder->getBindings()); + $this->assertEquals($builderClass, get_class($builder)); + } + + /** + * @test + * @dataProvider queryDataProvider + */ + public function alias_nested(Closure $query, string $builderClass) + { + $builder = $query(new EloquentPostModelStub) + ->joinRelation('image as photos.uploadedBy'); + + $this->assertEquals('select * from "posts" inner join "images" as "photos" on "photos"."imageable_id" = "posts"."id" and "photos"."imageable_type" = ? inner join "users" on "users"."id" = "photos"."uploaded_by_id"', $builder->toSql()); $this->assertEquals([0 => EloquentPostModelStub::class], $builder->getBindings()); $this->assertEquals($builderClass, get_class($builder)); }