Skip to content

Commit

Permalink
Merge pull request #32420 from LastDragon-ru/issue-31811
Browse files Browse the repository at this point in the history
[6.x] Fix `refresh()` to support `AsPivot` trait
  • Loading branch information
taylorotwell authored Apr 17, 2020
2 parents f5d6c43 + d54bb1e commit bb04588
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Jsonable;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection as BaseCollection;
Expand Down Expand Up @@ -1151,7 +1152,8 @@ public function refresh()
);

$this->load(collect($this->relations)->reject(function ($relation) {
return $relation instanceof Pivot;
return $relation instanceof Pivot
|| in_array(AsPivot::class, class_uses_recursive($relation), true);
})->keys()->all());

$this->syncOriginal();
Expand Down
35 changes: 35 additions & 0 deletions tests/Integration/Database/EloquentModelRefreshTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Illuminate\Tests\Integration\Database\EloquentModelRefreshTest;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Concerns\AsPivot;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Expand Down Expand Up @@ -57,6 +58,23 @@ public function testItSyncsOriginalOnRefresh()

$this->assertSame('patrick', $post->getOriginal('title'));
}

public function testAsPivot()
{
Schema::create('post_posts', function (Blueprint $table) {
$table->bigInteger('foreign_id');
$table->bigInteger('related_id');
});

$post = AsPivotPost::create(['title' => 'parent']);
$child = AsPivotPost::create(['title' => 'child']);

$post->children()->attach($child->getKey());

$this->assertEquals(1, $post->children->count());

$post->children->first()->refresh();
}
}

class Post extends Model
Expand All @@ -76,3 +94,20 @@ protected static function boot()
});
}
}

class AsPivotPost extends Post
{
public function children()
{
return $this
->belongsToMany(static::class, (new AsPivotPostPivot())->getTable(), 'foreign_id', 'related_id')
->using(AsPivotPostPivot::class);
}
}

class AsPivotPostPivot extends Model
{
use AsPivot;

protected $table = 'post_posts';
}

0 comments on commit bb04588

Please sign in to comment.