Skip to content

Commit

Permalink
Fix cloning the BelongsTo relationship.
Browse files Browse the repository at this point in the history
Closes #45.
  • Loading branch information
pavel-mironchik committed Dec 22, 2020
1 parent e813da3 commit 4feba23
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
12 changes: 9 additions & 3 deletions src/Cloner.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down Expand Up @@ -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();
}
});
}
}
15 changes: 15 additions & 0 deletions stubs/Image.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php namespace Bkwld\Cloner\Stubs;

use Bkwld\Cloner\Cloneable as Cloneable;

class Image extends Photo {
use Cloneable;

public $cloneable_relations = ['article'];

protected $table = 'photos';

public function onCloning() {
$this->uid = 2;
}
}
9 changes: 8 additions & 1 deletion tests/FunctionalTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 4feba23

Please sign in to comment.