diff --git a/src/Illuminate/Database/Eloquent/Model.php b/src/Illuminate/Database/Eloquent/Model.php index d3af4d08ddc5..c5b87aa7c735 100644 --- a/src/Illuminate/Database/Eloquent/Model.php +++ b/src/Illuminate/Database/Eloquent/Model.php @@ -1092,6 +1092,12 @@ public function push() return false; } + if (! $this->pushRelations( + $this->getRelationsOfType(BelongsToMany::class)->all() + )) { + return false; + } + return true; } @@ -1127,6 +1133,8 @@ protected function pushRelations($relations) if ($relation instanceof BelongsTo) { $relation->associate($model); + } elseif ($relation instanceof BelongsToMany) { + $relation->attach($model); } } } diff --git a/tests/Integration/Database/EloquentPushTest.php b/tests/Integration/Database/EloquentPushTest.php index 6434ef671f4a..592f38bece9e 100644 --- a/tests/Integration/Database/EloquentPushTest.php +++ b/tests/Integration/Database/EloquentPushTest.php @@ -24,6 +24,17 @@ protected function defineDatabaseMigrationsAfterDatabaseRefreshed() $table->unsignedInteger('user_id'); }); + Schema::create('tags', function (Blueprint $table) { + $table->increments('id'); + $table->string('tag'); + }); + + Schema::create('post_tag', function (Blueprint $table) { + $table->increments('id'); + $table->unsignedInteger('post_id'); + $table->unsignedInteger('tag_id'); + }); + Schema::create('post_details', function (Blueprint $table) { $table->increments('id'); $table->string('description'); @@ -141,6 +152,20 @@ public function testPushSavesAMorphToRelationship() $this->assertTrue($comment->commentable->is($post)); } + public function testPushSavesABelongsToManyRelationship() + { + $user = UserX::create(['name' => 'Mateus']); + $post = PostX::make(['title' => 'Test title', 'user_id' => $user->id]); + $tag = TagX::make(['tag' => 'Test tag']); + $post->tags->push($tag); + + $post->push(); + + $this->assertEquals(1, $post->id); + $this->assertEquals(1, $tag->id); + $this->assertTrue($post->tags->first()->is($tag)); + } + public function testPushReturnsFalseIfBelongsToSaveFails() { $post = PostX::make(['title' => 'Test title']); @@ -188,6 +213,11 @@ class PostX extends Model protected $guarded = []; protected $table = 'posts'; + public function tags() + { + return $this->belongsToMany(TagX::class, 'post_tag', 'post_id', 'tag_id'); + } + public function details() { return $this->hasOne(PostDetails::class, 'post_id'); @@ -232,3 +262,15 @@ public function commentable() return $this->morphTo('commentable'); } } + +class TagX extends Model +{ + public $timestamps = false; + protected $guarded = []; + protected $table = 'tags'; + + public function posts() + { + return $this->belongsToMany(PostX::class, 'post_tag', 'tag_id', 'post_id'); + } +}