Skip to content

Commit

Permalink
handle belongs to
Browse files Browse the repository at this point in the history
  • Loading branch information
mateusjatenee committed Nov 5, 2023
1 parent 0f3fbca commit ac3f1fe
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1092,6 +1092,12 @@ public function push()
return false;
}

if (! $this->pushRelations(
$this->getRelationsOfType(BelongsToMany::class)->all()
)) {
return false;
}

return true;
}

Expand Down Expand Up @@ -1127,6 +1133,8 @@ protected function pushRelations($relations)

if ($relation instanceof BelongsTo) {
$relation->associate($model);
} elseif ($relation instanceof BelongsToMany) {
$relation->attach($model);
}
}
}
Expand Down
42 changes: 42 additions & 0 deletions tests/Integration/Database/EloquentPushTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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']);
Expand Down Expand Up @@ -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');
Expand Down Expand Up @@ -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');
}
}

0 comments on commit ac3f1fe

Please sign in to comment.