File tree Expand file tree Collapse file tree 2 files changed +23
-3
lines changed
src/Jenssegers/Mongodb/Relations Expand file tree Collapse file tree 2 files changed +23
-3
lines changed Original file line number Diff line number Diff line change @@ -166,7 +166,7 @@ public function save(Model $model)
166166 $ this ->updateTimestamps ($ model );
167167
168168 // Insert a new document.
169- if ( ! $ model -> exists )
169+ if ( ! $ this -> contains ( $ model ) )
170170 {
171171 $ result = $ this ->performInsert ($ model );
172172 }
@@ -196,6 +196,22 @@ public function count()
196196 return count ($ this ->getEmbeddedRecords ());
197197 }
198198
199+ /**
200+ * Indicate if a model is already contained in the embedded documents
201+ *
202+ * @param \Illuminate\Database\Eloquent\Model $model
203+ * @return bool
204+ */
205+ public function contains (Model $ model )
206+ {
207+ foreach ($ this ->getEmbeddedRecords () as $ record )
208+ {
209+ if ($ record [$ model ->getKeyName ()] == $ model ->getKey ()) return true ;
210+ }
211+
212+ return false ;
213+ }
214+
199215 /**
200216 * Attach a model instance to the parent model without persistence.
201217 *
@@ -205,7 +221,7 @@ public function count()
205221 public function associate (Model $ model )
206222 {
207223 // Insert the related model in the parent instance
208- if ( ! $ model -> exists )
224+ if ( ! $ this -> contains ( $ model ) )
209225 {
210226 return $ this ->associateNew ($ model );
211227 }
Original file line number Diff line number Diff line change @@ -399,6 +399,10 @@ public function testEmbedsManyDuplicate()
399399 $ user ->addresses ()->save ($ address );
400400 $ this ->assertEquals (1 , $ user ->addresses ->count ());
401401 $ this ->assertEquals (array ('Paris ' ), $ user ->addresses ->lists ('city ' ));
402+
403+ $ user ->addresses ()->create (array ('_id ' => $ address ->_id , 'city ' => 'Bruxelles ' ));
404+ $ this ->assertEquals (1 , $ user ->addresses ->count ());
405+ $ this ->assertEquals (array ('Bruxelles ' ), $ user ->addresses ->lists ('city ' ));
402406 }
403407
404408 public function testEmbedsManyCreate ()
@@ -521,7 +525,7 @@ public function testEmbedsManyUpdatingEventReturnsFalse()
521525 {
522526 $ user = User::create (array ('name ' => 'John Doe ' ));
523527 $ address = new Address (array ('city ' => 'New York ' ));
524- $ address -> exists = true ;
528+ $ user -> addresses ()-> save ( $ address ) ;
525529
526530 $ address ->setEventDispatcher ($ events = Mockery::mock ('Illuminate\Events\Dispatcher ' ));
527531 $ events ->shouldReceive ('until ' )->once ()->with ('eloquent.saving: ' .get_class ($ address ), $ address )->andReturn (true );
You can’t perform that action at this time.
0 commit comments