Skip to content
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

[5.6] Added unsetRelation method to Eloquent models #24486

Merged
merged 3 commits into from
Jun 7, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/Illuminate/Database/Eloquent/Concerns/HasRelationships.php
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,21 @@ public function setRelation($relation, $value)
return $this;
}

/**
* Unset an existing relation.
*
* @param string $relation
* @return $this
*/
public function unsetRelation($relation)
{
if ($this->relationLoaded($relation)) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary? As long as $this->relations isn't null, unset($this->relations('foo')) will always work

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You are right, thought it could cause an undefined index error, will change

unset($this->relations[$relation]);
}

return $this;
}

/**
* Set the entire relations array on the model.
*
Expand Down
9 changes: 9 additions & 0 deletions tests/Database/DatabaseEloquentRelationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,15 @@ public function testSetRelationFail()
$this->assertArrayNotHasKey('foo', $parent->toArray());
}

public function testUnsetExistingRelation()
{
$parent = new EloquentRelationResetModelStub;
$relation = new EloquentRelationResetModelStub;
$parent->setRelation('foo', $relation);
$parent->unsetRelation('foo');
$this->assertFalse($parent->relationLoaded('foo'));
}

public function testTouchMethodUpdatesRelatedTimestamps()
{
$builder = m::mock(Builder::class);
Expand Down