File tree Expand file tree Collapse file tree 2 files changed +36
-2
lines changed
src/Jenssegers/Mongodb/Relations Expand file tree Collapse file tree 2 files changed +36
-2
lines changed Original file line number Diff line number Diff line change @@ -35,6 +35,25 @@ public function contains($key)
3535 return ($ embedded and $ embedded [$ primaryKey ] == $ key );
3636 }
3737
38+ /**
39+ * Associate the model instance to the given parent, without saving it to the database.
40+ *
41+ * @param \Illuminate\Database\Eloquent\Model $model
42+ * @return \Illuminate\Database\Eloquent\Model
43+ */
44+ public function associate (Model $ model )
45+ {
46+ // Create a new key if needed.
47+ if ( ! $ model ->getAttribute ('_id ' ))
48+ {
49+ $ model ->setAttribute ('_id ' , new MongoId );
50+ }
51+
52+ $ this ->setEmbedded ($ model ->getAttributes ());
53+
54+ return $ model ;
55+ }
56+
3857 /**
3958 * Save a new model and attach it to the parent model.
4059 *
@@ -51,7 +70,7 @@ protected function performInsert(Model $model)
5170
5271 $ result = $ this ->query ->update (array ($ this ->localKey => $ model ->getAttributes ()));
5372
54- if ($ result ) $ this ->setEmbedded ($ model-> getAttributes () );
73+ if ($ result ) $ this ->associate ($ model );
5574
5675 return $ result ? $ model : false ;
5776 }
@@ -66,7 +85,7 @@ protected function performUpdate(Model $model)
6685 {
6786 $ result = $ this ->query ->update (array ($ this ->localKey => $ model ->getAttributes ()));
6887
69- if ($ result ) $ this ->setEmbedded ($ model-> getAttributes () );
88+ if ($ result ) $ this ->associate ($ model );
7089
7190 return $ result ? $ model : false ;
7291 }
Original file line number Diff line number Diff line change @@ -414,6 +414,21 @@ public function testEmbedsOne()
414414 $ this ->assertEquals ('Jim Doe ' , $ user ->father ->name );
415415 }
416416
417+ public function testEmbedsOneAssociate ()
418+ {
419+ $ user = User::create (array ('name ' => 'John Doe ' ));
420+ $ father = new User (array ('name ' => 'Mark Doe ' ));
421+
422+ $ father ->setEventDispatcher ($ events = Mockery::mock ('Illuminate\Events\Dispatcher ' ));
423+ $ events ->shouldReceive ('until ' )->times (0 )->with ('eloquent.saving: ' .get_class ($ father ), $ father );
424+
425+ $ father = $ user ->father ()->associate ($ father );
426+ $ father ->unsetEventDispatcher ();
427+
428+ $ this ->assertNotNull ($ user ->_father );
429+ $ this ->assertEquals ('Mark Doe ' , $ user ->father ->name );
430+ }
431+
417432 public function testEmbedsOneDelete ()
418433 {
419434 $ user = User::create (array ('name ' => 'John Doe ' ));
You can’t perform that action at this time.
0 commit comments