Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Mixins/RelationshipsExtraMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -377,10 +377,11 @@ protected function performJoinForEloquentPowerJoinsForHasManyThrough()
$join->as($alias1);
}

$farParentTable = StaticCache::getTableOrAliasForModel($this->getFarParent());
$join->on(
"{$throughTable}.{$this->getFirstKeyName()}",
'=',
$this->getQualifiedLocalKeyName()
"{$farParentTable}.{$this->localKey}"
);

if ($disableExtraConditions === false && $this->usesSoftDeletes($this->getThroughParent())) {
Expand Down
31 changes: 31 additions & 0 deletions tests/JoinRelationshipUsingAliasTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -351,4 +351,35 @@ public function test_join_through_model_with_soft_deletes_using_alias()
$query
);
}

public function test_join_through_model_twice_using_alias()
{
// has many throuh
$query = Comment::joinRelationship('user.commentsThroughPosts', [
'user' => fn ($join) => $join->as('users_alias')->withTrashed(),
'commentsThroughPosts' => [
'posts' => fn ($join) => $join->as('posts_alias')->withTrashed(),
],
])->toSql();

// Expect users_alias.id to be used as the join key
$this->assertQueryContains(
'inner join "posts" as "posts_alias" on "posts_alias"."user_id" = "users_alias"."id"',
$query
);

// has one through
$query = Post::joinRelationship('comments.postCategory', [
'comments' => fn ($join) => $join->as('comments_alias')->withTrashed(),
'postCategory' => [
'posts' => fn ($join) => $join->as('posts_alias')->withTrashed(),
],
])->toSql();

// Expect comments_alias.post_id to be used as the join key
$this->assertQueryContains(
'inner join "posts" as "posts_alias" on "posts_alias"."id" = "comments_alias"."post_id"',
$query
);
}
}