Skip to content

Commit

Permalink
Allow the detach method to accept a collection (#14412)
Browse files Browse the repository at this point in the history
  • Loading branch information
Aaron Costello authored and taylorotwell committed Jul 21, 2016
1 parent be43de2 commit 9d853b9
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
10 changes: 7 additions & 3 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -1061,14 +1061,18 @@ protected function setTimestampsOnAttach(array $record, $exists = false)
/**
* Detach models from the relationship.
*
* @param int|array $ids
* @param mixed $ids
* @param bool $touch
* @return int
*/
public function detach($ids = [], $touch = true)
{
if ($ids instanceof Model) {
$ids = (array) $ids->getKey();
$ids = $ids->getKey();
}

if ($ids instanceof Collection) {
$ids = $ids->modelKeys();
}

$query = $this->newPivotQuery();
Expand All @@ -1079,7 +1083,7 @@ public function detach($ids = [], $touch = true)
$ids = (array) $ids;

if (count($ids) > 0) {
$query->whereIn($this->otherKey, (array) $ids);
$query->whereIn($this->otherKey, $ids);
}

// Once we have all of the conditions set on the statement, we are ready
Expand Down
21 changes: 21 additions & 0 deletions tests/Database/DatabaseEloquentBelongsToManyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,27 @@ public function testDetachWithSingleIDRemovesPivotTableRecord()
$this->assertTrue($relation->detach([1]));
}

public function testDetachMethodConvertsCollectionToArrayOfKeys()
{
$relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['touchIfTouching'], $this->getRelationArguments());
$query = m::mock('stdClass');
$query->shouldReceive('from')->once()->with('user_role')->andReturn($query);
$query->shouldReceive('where')->once()->with('user_id', 1)->andReturn($query);
$query->shouldReceive('whereIn')->once()->with('role_id', [1, 2, 3]);
$query->shouldReceive('delete')->once()->andReturn(true);
$relation->getQuery()->shouldReceive('getQuery')->andReturn($mockQueryBuilder = m::mock('StdClass'));
$mockQueryBuilder->shouldReceive('newQuery')->once()->andReturn($query);
$relation->expects($this->once())->method('touchIfTouching');

$collection = new Collection([
m::mock(['getKey' => 1]),
m::mock(['getKey' => 2]),
m::mock(['getKey' => 3]),
]);

$this->assertTrue($relation->detach($collection));
}

public function testDetachMethodClearsAllPivotRecordsWhenNoIDsAreGiven()
{
$relation = $this->getMock('Illuminate\Database\Eloquent\Relations\BelongsToMany', ['touchIfTouching'], $this->getRelationArguments());
Expand Down

0 comments on commit 9d853b9

Please sign in to comment.