From 4feba23139215e19c17d423fa608f49edede05e9 Mon Sep 17 00:00:00 2001 From: Pavel Mironchik Date: Tue, 22 Dec 2020 22:05:27 +0600 Subject: [PATCH] Fix cloning the BelongsTo relationship. Closes #45. --- src/Cloner.php | 12 +++++++++--- stubs/Image.php | 15 +++++++++++++++ tests/FunctionalTest.php | 9 ++++++++- 3 files changed, 32 insertions(+), 4 deletions(-) create mode 100644 stubs/Image.php 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