Skip to content

Commit 32ec75f

Browse files
authored
fix alias not applying in "through" joins when referencing the same table twice (#222)
1 parent d67c7e2 commit 32ec75f

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/Mixins/RelationshipsExtraMethods.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,10 +377,11 @@ protected function performJoinForEloquentPowerJoinsForHasManyThrough()
377377
$join->as($alias1);
378378
}
379379

380+
$farParentTable = StaticCache::getTableOrAliasForModel($this->getFarParent());
380381
$join->on(
381382
"{$throughTable}.{$this->getFirstKeyName()}",
382383
'=',
383-
$this->getQualifiedLocalKeyName()
384+
"{$farParentTable}.{$this->localKey}"
384385
);
385386

386387
if ($disableExtraConditions === false && $this->usesSoftDeletes($this->getThroughParent())) {

tests/JoinRelationshipUsingAliasTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,4 +351,35 @@ public function test_join_through_model_with_soft_deletes_using_alias()
351351
$query
352352
);
353353
}
354+
355+
public function test_join_through_model_twice_using_alias()
356+
{
357+
// has many throuh
358+
$query = Comment::joinRelationship('user.commentsThroughPosts', [
359+
'user' => fn ($join) => $join->as('users_alias')->withTrashed(),
360+
'commentsThroughPosts' => [
361+
'posts' => fn ($join) => $join->as('posts_alias')->withTrashed(),
362+
],
363+
])->toSql();
364+
365+
// Expect users_alias.id to be used as the join key
366+
$this->assertQueryContains(
367+
'inner join "posts" as "posts_alias" on "posts_alias"."user_id" = "users_alias"."id"',
368+
$query
369+
);
370+
371+
// has one through
372+
$query = Post::joinRelationship('comments.postCategory', [
373+
'comments' => fn ($join) => $join->as('comments_alias')->withTrashed(),
374+
'postCategory' => [
375+
'posts' => fn ($join) => $join->as('posts_alias')->withTrashed(),
376+
],
377+
])->toSql();
378+
379+
// Expect comments_alias.post_id to be used as the join key
380+
$this->assertQueryContains(
381+
'inner join "posts" as "posts_alias" on "posts_alias"."id" = "comments_alias"."post_id"',
382+
$query
383+
);
384+
}
354385
}

0 commit comments

Comments
 (0)