From acebcfcbcda7a9fc6e64a05ec89cab0f5088a0af Mon Sep 17 00:00:00 2001 From: James Freeman Date: Tue, 27 Apr 2021 21:14:20 +0100 Subject: [PATCH] [8.x] Add withOnly method (#37144) * Added in new withOnly method + tests * Refactored function * Update Builder.php Co-authored-by: Taylor Otwell --- src/Illuminate/Database/Eloquent/Builder.php | 13 +++++++++++++ tests/Database/DatabaseEloquentModelTest.php | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/src/Illuminate/Database/Eloquent/Builder.php b/src/Illuminate/Database/Eloquent/Builder.php index a8f2fb87842c..a26a70ef0dd1 100755 --- a/src/Illuminate/Database/Eloquent/Builder.php +++ b/src/Illuminate/Database/Eloquent/Builder.php @@ -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. * diff --git a/tests/Database/DatabaseEloquentModelTest.php b/tests/Database/DatabaseEloquentModelTest.php index 4c2210be5106..0efd4d8fff2c 100755 --- a/tests/Database/DatabaseEloquentModelTest.php +++ b/tests/Database/DatabaseEloquentModelTest.php @@ -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;