diff --git a/src/Cloner.php b/src/Cloner.php index fa91e16..6454074 100644 --- a/src/Cloner.php +++ b/src/Cloner.php @@ -49,7 +49,9 @@ public function duplicate($model, $relation = null) { $this->dispatchOnCloningEvent($clone, $relation, $model); if ($relation) { - $relation->save($clone); + if (!is_a($relation, 'Illuminate\Database\Eloquent\Relations\BelongsTo')) { + $relation->save($clone); + } } else { $clone->save(); } @@ -210,7 +212,11 @@ protected function duplicatePivotedRelation($relation, $relation_name, $clone) { */ protected function duplicateDirectRelation($relation, $relation_name, $clone) { $relation->get()->each(function($foreign) use ($clone, $relation_name) { - $this->duplicate($foreign, $clone->$relation_name()); - }); + $cloned_relation = $this->duplicate($foreign, $clone->$relation_name()); + if (is_a($clone->$relation_name(), 'Illuminate\Database\Eloquent\Relations\BelongsTo')) { + $clone->$relation_name()->associate($cloned_relation); + $clone->save(); + } + }); } } diff --git a/stubs/Image.php b/stubs/Image.php new file mode 100644 index 0000000..aabf37a --- /dev/null +++ b/stubs/Image.php @@ -0,0 +1,15 @@ +uid = 2; + } +} diff --git a/tests/FunctionalTest.php b/tests/FunctionalTest.php index d8861c1..d267c9e 100644 --- a/tests/FunctionalTest.php +++ b/tests/FunctionalTest.php @@ -5,6 +5,7 @@ use Bkwld\Cloner\Adapters\Upchuck; use Bkwld\Cloner\Stubs\Article; use Bkwld\Cloner\Stubs\Author; +use Bkwld\Cloner\Stubs\Image; use Bkwld\Cloner\Stubs\Photo; use Bkwld\Cloner\Stubs\User; use Bkwld\Upchuck\Helpers; @@ -212,7 +213,13 @@ function testExists() $path = $this->helpers->path($photo->image); $this->assertTrue($this->disk->has($path)); $this->assertEquals('contents', $this->disk->read($path)); - } + + // Test one to many inverse (BelongsTo) + $image = Image::first(); + $clone = $cloner->duplicate($image); + $this->assertNotNull($clone->article); + $this->assertNotEquals($this->article->id, $clone->article->id); + } // Test that model is created in a differetnt database. These checks don't // use eloquent because Laravel has issues with relationships on models in