From 4edde495b9fe494d06ae778734b82d1630bfa576 Mon Sep 17 00:00:00 2001 From: Sharptsa Date: Fri, 18 Jan 2019 18:37:31 +0100 Subject: [PATCH] use the localKey or the ownerKey of the relation instead of the primaryKey of the model --- src/EloquentJoinBuilder.php | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/src/EloquentJoinBuilder.php b/src/EloquentJoinBuilder.php index 96383b7..53b0d3c 100644 --- a/src/EloquentJoinBuilder.php +++ b/src/EloquentJoinBuilder.php @@ -150,9 +150,10 @@ private function performJoin($relations, $leftJoin = null) $joinQuery = $relatedTable.($this->useTableAlias ? ' as '.$relatedTableAlias : ''); if ($relatedRelation instanceof BelongsToJoin) { $relatedKey = $relatedRelation->getForeignKey(); + $ownerKey = $relatedRelation->getOwnerKey(); - $this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $relatedPrimaryKey, $currentTableAlias, $relatedKey) { - $join->on($relatedTableAlias.'.'.$relatedPrimaryKey, '=', $currentTableAlias.'.'.$relatedKey); + $this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $ownerKey, $currentTableAlias, $relatedKey) { + $join->on($relatedTableAlias.'.'.$ownerKey, '=', $currentTableAlias.'.'.$relatedKey); $this->joinQuery($join, $relatedRelation, $relatedTableAlias); }); @@ -160,8 +161,11 @@ private function performJoin($relations, $leftJoin = null) $relatedKey = $relatedRelation->getQualifiedForeignKeyName(); $relatedKey = last(explode('.', $relatedKey)); - $this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $relatedPrimaryKey, $currentTableAlias, $relatedKey, $currentPrimaryKey) { - $join->on($relatedTableAlias.'.'.$relatedKey, '=', $currentTableAlias.'.'.$currentPrimaryKey); + $localKey = $relatedRelation->getQualifiedParentKeyName(); + $localKey = last(explode('.', $localKey)); + + $this->$joinMethod($joinQuery, function ($join) use ($relatedRelation, $relatedTableAlias, $relatedKey, $currentTableAlias, $localKey) { + $join->on($relatedTableAlias.'.'.$relatedKey, '=', $currentTableAlias.'.'.$localKey); $this->joinQuery($join, $relatedRelation, $relatedTableAlias); });