diff --git a/src/Jenssegers/Mongodb/Relations/EmbedsMany.php b/src/Jenssegers/Mongodb/Relations/EmbedsMany.php index a4e2e73f90eb71d0dbc94ea50c04957acbf7beaa..774e471fdd410b3a1377710a2751809eb1070ab7 100644 --- a/src/Jenssegers/Mongodb/Relations/EmbedsMany.php +++ b/src/Jenssegers/Mongodb/Relations/EmbedsMany.php @@ -166,7 +166,7 @@ class EmbedsMany extends Relation { $this->updateTimestamps($model); // Insert a new document. - if ( ! $model->exists) + if ( ! $this->contains($model)) { $result = $this->performInsert($model); } @@ -196,6 +196,22 @@ class EmbedsMany extends Relation { return count($this->getEmbeddedRecords()); } + /** + * Indicate if a model is already contained in the embedded documents + * + * @param \Illuminate\Database\Eloquent\Model $model + * @return bool + */ + public function contains(Model $model) + { + foreach ($this->getEmbeddedRecords() as $record) + { + if ($record[$model->getKeyName()] == $model->getKey()) return true; + } + + return false; + } + /** * Attach a model instance to the parent model without persistence. * @@ -205,7 +221,7 @@ class EmbedsMany extends Relation { public function associate(Model $model) { // Insert the related model in the parent instance - if ( ! $model->exists) + if ( ! $this->contains($model)) { return $this->associateNew($model); } diff --git a/tests/RelationsTest.php b/tests/RelationsTest.php index 9c5f763bb0801687f4f777043a8a25c454a6e586..2773b1be52e411d2c190e2f2806509decc2b47e0 100644 --- a/tests/RelationsTest.php +++ b/tests/RelationsTest.php @@ -399,6 +399,10 @@ class RelationsTest extends TestCase { $user->addresses()->save($address); $this->assertEquals(1, $user->addresses->count()); $this->assertEquals(array('Paris'), $user->addresses->lists('city')); + + $user->addresses()->create(array('_id' => $address->_id, 'city' => 'Bruxelles')); + $this->assertEquals(1, $user->addresses->count()); + $this->assertEquals(array('Bruxelles'), $user->addresses->lists('city')); } public function testEmbedsManyCreate() @@ -521,7 +525,7 @@ class RelationsTest extends TestCase { { $user = User::create(array('name' => 'John Doe')); $address = new Address(array('city' => 'New York')); - $address->exists = true; + $user->addresses()->save($address); $address->setEventDispatcher($events = Mockery::mock('Illuminate\Events\Dispatcher')); $events->shouldReceive('until')->once()->with('eloquent.saving: '.get_class($address), $address)->andReturn(true);