Skip to content

Commit

Permalink
+ Added support for mixed join types
Browse files Browse the repository at this point in the history
  • Loading branch information
tylernathanreed committed Jul 25, 2021
1 parent e1ca07d commit 028f6d0
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,13 @@ User::query()->joinRelation('posts as articles.comments as threads', [
});
```

The join type can also be mixed:
```php
User::query()->joinRelation('posts.comments', [
'comments' => function ($join) { $join->type = 'left'; }
});
```

<a name="multiple-constraints-through"></a>
#### Through-Syntax

Expand Down
29 changes: 28 additions & 1 deletion src/Mixins/JoinsRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,10 @@ public function joinRelation()
$this->applyJoinScopes($joinQuery);
}

$joinType = $joinQuery->getJoinType();

$this->addJoinRelationWhere(
$joinQuery, $relation, $type
$joinQuery, $relation, $joinType ?: $type
);

return ! is_null($relatedQuery) ? $joinQuery : $this;
Expand Down Expand Up @@ -232,6 +234,31 @@ protected function callJoinScope()
};
}

/**
* Defines the mixin for {@see $query->getJoinType()}.
*
* @return \Closure
*/
protected function getJoinType()
{
/**
* Returns the custom provided join type.
*
* @return string|null
*/
return function () {
if (! property_exists($this, 'type')) {
return null;
}

try {
$type = $this->type;
} finally {
return $type;
}
};
}

/**
* Defines the mixin for {@see $query->addJoinRelationWhere()}.
*
Expand Down
16 changes: 16 additions & 0 deletions tests/Unit/JoinsRelationshipsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,20 @@ public function multiconstraint_skip_middle_associative(Closure $query, string $
$this->assertEquals([true, 'thumbs-up'], $builder->getBindings());
$this->assertEquals($builderClass, get_class($builder));
}

/**
* @test
* @dataProvider queryDataProvider
*/
public function multiconstraint_mix_type(Closure $query, string $builderClass)
{
$builder = $query(new EloquentUserModelStub)
->joinRelation('posts.comments.likes', [
'posts' => function ($join) { $join->type = 'left'; },
'likes' => function ($join) { $join->type = 'right'; }
]);

$this->assertEquals('select * from "users" left join "posts" on "posts"."user_id" = "users"."id" inner join "comments" on "comments"."post_id" = "posts"."id" right join "likes" on "likes"."comment_id" = "comments"."id"', $builder->toSql());
$this->assertEquals($builderClass, get_class($builder));
}
}

0 comments on commit 028f6d0

Please sign in to comment.