Skip to content

Commit

Permalink
[8.x] Add withOnly method (#37144)
Browse files Browse the repository at this point in the history
* Added in new withOnly method + tests

* Refactored function

* Update Builder.php

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
JamesFreeman and taylorotwell authored Apr 27, 2021
1 parent 041f016 commit acebcfc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Database/Eloquent/Builder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1236,6 +1236,19 @@ public function without($relations)
return $this;
}

/**
* Set the relationships that should be eager loaded while removing any previously added eager loading specifications.
*
* @param mixed $relations
* @return $this
*/
public function withOnly($relations)
{
$this->eagerLoad = [];

return $this->with($relations);
}

/**
* Create a new instance of the model being queried.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,15 @@ public function testWithoutMethodRemovesEagerLoadedRelationshipCorrectly()
$this->assertEmpty($instance->getEagerLoads());
}

public function testWithOnlyMethodLoadsRelationshipCorrectly()
{
$model = new EloquentModelWithoutRelationStub();
$this->addMockConnection($model);
$instance = $model->newInstance()->newQuery()->withOnly('taylor');
$this->assertNotNull($instance->getEagerLoads()['taylor']);
$this->assertArrayNotHasKey('foo', $instance->getEagerLoads());
}

public function testEagerLoadingWithColumns()
{
$model = new EloquentModelWithoutRelationStub;
Expand Down

0 comments on commit acebcfc

Please sign in to comment.