Skip to content

Commit b2e0fd7

Browse files
committed
Adding some alias methods for embedsMany
1 parent de3ffe0 commit b2e0fd7

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

src/Jenssegers/Mongodb/Relations/EmbedsMany.php

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,14 +290,19 @@ public function createMany(array $records)
290290
* @param array|int $ids
291291
* @return int
292292
*/
293-
public function destroy($ids)
293+
public function destroy($ids = array())
294294
{
295295
// We'll initialize a count here so we will return the total number of deletes
296296
// for the operation. The developers can then check this number as a boolean
297297
// type value or get this total count of records deleted for logging, etc.
298298
$count = 0;
299299

300-
$ids = is_array($ids) ? $ids : func_get_args();
300+
if ($ids instanceof Model) $ids = (array) $ids->getKey();
301+
302+
// If associated IDs were passed to the method we will only delete those
303+
// associations, otherwise all of the association ties will be broken.
304+
// We'll return the numbers of affected rows when we do the deletes.
305+
$ids = (array) $ids;
301306

302307
// Get existing embedded documents.
303308
$documents = $this->getEmbedded();
@@ -320,6 +325,28 @@ public function destroy($ids)
320325
return $count;
321326
}
322327

328+
/**
329+
* Delete alias.
330+
*
331+
* @param int|array $ids
332+
* @return int
333+
*/
334+
public function detach($ids = array())
335+
{
336+
return $this->destroy($ids);
337+
}
338+
339+
/**
340+
* Save alias.
341+
*
342+
* @param \Illuminate\Database\Eloquent\Model $model
343+
* @return \Illuminate\Database\Eloquent\Model
344+
*/
345+
public function attach(Model $model)
346+
{
347+
return $this->save($model);
348+
}
349+
323350
/**
324351
* Get the embedded documents array
325352
*

tests/RelationsTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,22 @@ public function testEmbedsManyDestroy()
342342
$address = $user->addresses->first();
343343
$user->addresses()->destroy($address->_id);
344344
$this->assertEquals(array('Bristol', 'Bruxelles'), $user->addresses->lists('city'));
345+
346+
$address = $user->addresses->first();
347+
$user->addresses()->destroy($address);
348+
$this->assertEquals(array('Bruxelles'), $user->addresses->lists('city'));
349+
}
350+
351+
public function testEmbedsManyAliases()
352+
{
353+
$user = User::create(array('name' => 'John Doe'));
354+
$address = new Address(array('city' => 'London'));
355+
356+
$address = $user->addresses()->attach($address);
357+
$this->assertEquals(array('London'), $user->addresses->lists('city'));
358+
359+
$user->addresses()->detach($address);
360+
$this->assertEquals(array(), $user->addresses->lists('city'));
345361
}
346362

347363
}

0 commit comments

Comments
 (0)