Skip to content

Commit

Permalink
~ Fixed morphOne aliasing
Browse files Browse the repository at this point in the history
  • Loading branch information
tylernathanreed committed Apr 1, 2023
1 parent 3b001f6 commit d6e2580
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
8 changes: 7 additions & 1 deletion src/RelationJoinQuery.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
);
}

Expand Down
20 changes: 17 additions & 3 deletions tests/Unit/MorphOneTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down

0 comments on commit d6e2580

Please sign in to comment.