Skip to content

Commit

Permalink
[6.x] Implement withoutRelations method (#30802)
Browse files Browse the repository at this point in the history
* Implement withoutRelations method

This will allow to unload all of the model's relations so it can be used, for example, to not overload queued jobs.

* Rework to clone object
  • Loading branch information
driesvints authored and taylorotwell committed Dec 10, 2019
1 parent 454c2b3 commit e32442b
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -722,6 +722,30 @@ protected function newRelatedInstance($class)
});
}

/**
* Duplicate the instance and unset all the loaded relations.
*
* @return $this
*/
public function withoutRelations()
{
$model = clone $this;

return $model->unsetRelations();
}

/**
* Unset all the loaded relations for the instance.
*
* @return $this
*/
public function unsetRelations()
{
$this->relations = [];

return $this;
}

/**
* Get all the loaded relations for the instance.
*
Expand Down
21 changes: 21 additions & 0 deletions tests/Database/DatabaseEloquentRelationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,27 @@ public function testSettingMorphMapWithNumericKeys()
Relation::morphMap([], false);
}

public function testWithoutRelations()
{
$original = new EloquentNoTouchingModelStub;

$original->setRelation('foo', 'baz');

$this->assertEquals('baz', $original->getRelation('foo'));

$model = $original->withoutRelations();

$this->assertInstanceOf(EloquentNoTouchingModelStub::class, $model);
$this->assertTrue($original->relationLoaded('foo'));
$this->assertFalse($model->relationLoaded('foo'));

$model = $original->unsetRelations();

$this->assertInstanceOf(EloquentNoTouchingModelStub::class, $model);
$this->assertFalse($original->relationLoaded('foo'));
$this->assertFalse($model->relationLoaded('foo'));
}

public function testMacroable()
{
Relation::macro('foo', function () {
Expand Down

0 comments on commit e32442b

Please sign in to comment.