diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index 45bd5bf47489..bf7d1c96c004 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -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; @@ -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(); diff --git a/tests/Integration/Database/EloquentModelRefreshTest.php b/tests/Integration/Database/EloquentModelRefreshTest.php index 0fdfa8781996..8fb2bcb95180 100644 --- a/tests/Integration/Database/EloquentModelRefreshTest.php +++ b/tests/Integration/Database/EloquentModelRefreshTest.php @@ -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; @@ -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 @@ -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'; +}