Skip to content

Commit

Permalink
Handle single model in sync method; (#2648)
Browse files Browse the repository at this point in the history
  • Loading branch information
hans-thomas committed Nov 3, 2023
1 parent 744c8ae commit 0cdba6a
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ public function sync($ids, $detaching = true)

if ($ids instanceof Collection) {
$ids = $ids->modelKeys();
} elseif ($ids instanceof Model) {
$ids = $this->parseIds($ids);
}

// First we need to attach any of the associated models that are not currently
Expand Down
30 changes: 30 additions & 0 deletions tests/RelationsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,36 @@ public function testBelongsToMany(): void
$this->assertCount(1, $client->users);
}

public function testSyncBelongsToMany()
{
$user = User::create(['name' => 'John Doe']);

$first = Client::query()->create(['name' => 'Hans']);
$second = Client::query()->create(['name' => 'Thomas']);

$user->load('clients');
self::assertEmpty($user->clients);

$user->clients()->sync($first);

$user->load('clients');
self::assertCount(1, $user->clients);
self::assertTrue($user->clients->first()->is($first));

$user->clients()->sync($second);

$user->load('clients');
self::assertCount(1, $user->clients);
self::assertTrue($user->clients->first()->is($second));

$user->clients()->syncWithoutDetaching($first);

$user->load('clients');
self::assertCount(2, $user->clients);
self::assertTrue($user->clients->first()->is($first));
self::assertTrue($user->clients->last()->is($second));
}

public function testBelongsToManyAttachesExistingModels(): void
{
$user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]);
Expand Down

0 comments on commit 0cdba6a

Please sign in to comment.