-
Notifications
You must be signed in to change notification settings - Fork 11.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[10.x] Add JoinMany
and JoinOne
methods for joining Models to Builder
#46603
Closed
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
4c9ea8e
Add hasMany and HasOne to join models
joelharkes bc7f5c4
Fix sql grammar for nested joins
joelharkes 1c219ca
Fix proper scoping in join statements to make left joins work properly
joelharkes 7832ce3
Add test cases for primary key name
joelharkes ee5f8cb
Fix docs
joelharkes 80e5ff9
Add test for relationship
joelharkes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
102 changes: 102 additions & 0 deletions
102
src/Illuminate/Database/Eloquent/Concerns/JoinsModels.php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Illuminate\Database\Eloquent\Concerns; | ||
|
||
use Illuminate\Database\Eloquent\Builder; | ||
use Illuminate\Database\Eloquent\Model; | ||
use Illuminate\Database\Eloquent\Relations\Relation; | ||
use Illuminate\Database\Eloquent\Scope; | ||
use Illuminate\Database\Query\JoinClause; | ||
use Illuminate\Support\Str; | ||
|
||
trait JoinsModels | ||
{ | ||
/** | ||
* @param class-string<Model>|Model|Builder<Model> $model | ||
* @param string $joinType | ||
* @param string|null $overrideJoinColumnName | ||
* @return static | ||
*/ | ||
public function joinMany($model, string $joinType = 'inner', ?string $overrideJoinColumnName = null): static { | ||
/** @var Builder $builder */ | ||
$builder = match(true) { | ||
is_string($model) => (new $model())->newQuery(), | ||
$model instanceof Builder => $model, | ||
$model instanceof Model => $model->newQuery(), | ||
$model instanceof Relation => $model->getQuery(), | ||
}; | ||
|
||
return $this->joinManyOn($this->getModel(), $builder, $joinType,null, $overrideJoinColumnName); | ||
} | ||
|
||
/** | ||
* @param class-string|Model|Builder<Model> $model | ||
* @param string $joinType | ||
* @param string|null $overrideBaseColumn | ||
* @return static | ||
*/ | ||
public function joinOne($model, string $joinType = 'inner', ?string $overrideBaseColumn = null): static { | ||
$builder = match(true) { | ||
is_string($model) => (new $model())->newQuery(), | ||
$model instanceof Builder => $model, | ||
$model instanceof Model => $model->newQuery(), | ||
$model instanceof Relation => $model->getQuery(), | ||
}; | ||
|
||
$this->joinOneOn($this->getModel(), $builder, $joinType, $overrideBaseColumn); | ||
|
||
return $this; | ||
} | ||
|
||
|
||
private function joinManyOn(Model $baseModel, Builder $builderToJoin, ?string $joinType = 'inner', ?string $overrideBaseColumnName = null, ?string $overrideJoinColumnName = null): static | ||
{ | ||
$modelToJoin = $builderToJoin->getModel(); | ||
$manyJoinColumnName = $overrideJoinColumnName ?? (Str::singular($baseModel->getTable()). '_' . $baseModel->getKeyName()); | ||
$baseColumnName = $overrideBaseColumnName ?? $baseModel->getKeyName(); | ||
$this->join( | ||
$modelToJoin->getTable(), fn(JoinClause $join) => | ||
$join->on( | ||
$modelToJoin->qualifyColumn($manyJoinColumnName), | ||
'=', | ||
$baseModel->qualifyColumn($baseColumnName), | ||
)->addNestedWhereQuery($builderToJoin->applyScopes()->getQuery()), | ||
type: $joinType | ||
); | ||
|
||
return $this; | ||
} | ||
|
||
private function joinOneOn(Model $baseModel, Builder $builderToJoin, string $joinType = 'inner', string $overrideBaseColumnName = null, string $overrideJoinColumnName = null): static | ||
{ | ||
$modelToJoin = $builderToJoin->getModel(); | ||
$joinColumnName = $overrideBaseColumnName ?? $modelToJoin->getKeyName(); | ||
$baseColumnName = $overrideJoinColumnName ?? (Str::singular($modelToJoin->getTable()). '_' . $modelToJoin->getKeyName()); | ||
$this->join( | ||
$modelToJoin->getTable(), fn(JoinClause $join) => | ||
$join->on( | ||
$modelToJoin->qualifyColumn($joinColumnName), | ||
'=', | ||
$baseModel->qualifyColumn($baseColumnName), | ||
)->addNestedWhereQuery($builderToJoin->getQuery()), | ||
type: $joinType | ||
); | ||
$this->applyScopesWith($builderToJoin->getScopes(), $modelToJoin); | ||
return $this; | ||
} | ||
|
||
/** | ||
* @param Scope[] $scopes | ||
* @param Model $model | ||
* @return static | ||
*/ | ||
private function applyScopesWith(array $scopes, Model $model): static | ||
{ | ||
foreach($scopes as $scope){ | ||
$scope->apply($this, $model); | ||
} | ||
return $this; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -504,9 +504,10 @@ protected function whereNested(Builder $query, $where) | |
// Here we will calculate what portion of the string we need to remove. If this | ||
// is a join clause query, we need to remove the "on" portion of the SQL and | ||
// if it is a normal query we need to take the leading "where" of queries. | ||
$offset = $query instanceof JoinClause ? 3 : 6; | ||
$whereSql = $this->compileWheres($where['query']); | ||
$offset = $query instanceof JoinClause && str_starts_with($whereSql, 'on ') ? 3 : 6; | ||
|
||
return '('.substr($this->compileWheres($where['query']), $offset).')'; | ||
return '('.substr($whereSql, $offset).')'; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. this was actually a bug, nested inner where's would be cut off on 'whe' and still leave 're ' in the query |
||
} | ||
|
||
/** | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace Illuminate\Tests\Database; | ||
|
||
use Illuminate\Database\Capsule\Manager as DB; | ||
use Illuminate\Database\Eloquent\Builder; | ||
use Illuminate\Database\Eloquent\Model; | ||
use Illuminate\Database\Eloquent\SoftDeletes; | ||
use PHPUnit\Framework\TestCase; | ||
|
||
class DatabaseEloquentJoinsModelsTest extends TestCase | ||
{ | ||
private DB $db; | ||
|
||
protected function setUp(): void | ||
{ | ||
$db = new DB; | ||
|
||
$db->addConnection([ | ||
'driver' => 'sqlite', | ||
'database' => ':memory:', | ||
]); | ||
|
||
$db->bootEloquent(); | ||
$db->setAsGlobal(); | ||
$this->db = $db; | ||
} | ||
protected function tearDown(): void | ||
{ | ||
\Mockery::close(); | ||
} | ||
public function testJoinMany() | ||
{ | ||
$mock = \Mockery::mock(Builder::class, [$this->db->getDatabaseManager()->query()])->makePartial(); | ||
$mock->shouldReceive('join')->withSomeOfArgs('comments')->andReturn($mock)->once(); | ||
$query =$mock->setModel(new Blog()); | ||
$query->joinMany(Comment::class); | ||
\Mockery::close(); | ||
} | ||
|
||
public function testJoinOne() | ||
{ | ||
$mock = \Mockery::mock(Builder::class, [$this->db->getDatabaseManager()->query()])->makePartial(); | ||
$mock->shouldReceive('join')->withSomeOfArgs('blogs')->andReturn($mock)->once(); | ||
$query = $mock->setModel(new Comment()); | ||
$query->joinOne(Blog::class); | ||
\Mockery::close(); | ||
} | ||
|
||
public function testSimpleHasMany() | ||
{ | ||
$blog = new Blog(); | ||
$query = $blog->newQuery()->joinMany(Comment::class)->toSql(); | ||
$this->assertSame('select * from "blogs" inner join "comments" on "comments"."blog_id" = "blogs"."id"', $query); | ||
} | ||
|
||
public function testSimpleHasOne() | ||
{ | ||
$query = (new Comment())->newQuery()->joinOne(Blog::class)->toSql(); | ||
$this->assertSame('select * from "comments" inner join "blogs" on "blogs"."id" = "comments"."blog_id"', $query); | ||
} | ||
|
||
public function testSimpleHasManyAlternativePrimaryKeyName() | ||
{ | ||
$blog = new Alternative(); | ||
$query = $blog->newQuery()->joinMany(Blog::class)->toSql(); | ||
$this->assertSame('select * from "alternatives" inner join "blogs" on "blogs"."alternative_key" = "alternatives"."key"', $query); | ||
} | ||
|
||
public function testIncludeScopesInJoin() | ||
{ | ||
$blog = new Blog(); | ||
$query = $blog->newQuery()->joinMany(DeletableComment::class)->toSql(); | ||
$this->assertSame('select * from "blogs" inner join "deletable_comments" on "deletable_comments"."blog_id" = "blogs"."id" and ("deletable_comments"."deleted_at" is null)', $query); | ||
} | ||
|
||
public function testCanJoinBuilder() | ||
{ | ||
$blog = new Blog(); | ||
$query = $blog->newQuery()->joinMany(DeletableComment::withTrashed())->toSql(); | ||
$this->assertSame('select * from "blogs" inner join "deletable_comments" on "deletable_comments"."blog_id" = "blogs"."id"', $query); | ||
} | ||
|
||
public function testAddWhereStatements() | ||
{ | ||
$blog = new Blog(); | ||
$query = $blog->newQuery()->joinMany(Comment::query()->whereNull('comments.deleted_at'))->toSql(); | ||
$this->assertSame('select * from "blogs" inner join "comments" on "comments"."blog_id" = "blogs"."id" and ("comments"."deleted_at" is null)', $query); | ||
} | ||
|
||
public function testAddingOnRelation() | ||
{ | ||
$blog = new Blog(); | ||
$query = $blog->comments()->joinOne(User::class)->toSql(); | ||
$this->assertSame('select * from "comments" inner join "users" on "users"."id" = "comments"."user_id" where "comments"."blog_id" is null and "comments"."blog_id" is not null', $query); | ||
} | ||
} | ||
|
||
|
||
class Blog extends Model { | ||
public function comments(){ | ||
return $this->hasMany(Comment::class); | ||
} | ||
} | ||
class Comment extends Model {} | ||
class User extends Model {} | ||
|
||
class DeletableComment extends Model { | ||
use SoftDeletes; | ||
} | ||
|
||
class Alternative extends Model | ||
{ | ||
protected $primaryKey = 'key'; | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Relations actually don't work very well yet (see PR description), i could remove this for now so it would just throw an exception instead?