Skip to content

Commit 0cdba6a

Browse files
authored
Handle single model in sync method; (#2648)
1 parent 744c8ae commit 0cdba6a

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/Relations/BelongsToMany.php

+2
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,8 @@ public function sync($ids, $detaching = true)
117117

118118
if ($ids instanceof Collection) {
119119
$ids = $ids->modelKeys();
120+
} elseif ($ids instanceof Model) {
121+
$ids = $this->parseIds($ids);
120122
}
121123

122124
// First we need to attach any of the associated models that are not currently

tests/RelationsTest.php

+30
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,36 @@ public function testBelongsToMany(): void
255255
$this->assertCount(1, $client->users);
256256
}
257257

258+
public function testSyncBelongsToMany()
259+
{
260+
$user = User::create(['name' => 'John Doe']);
261+
262+
$first = Client::query()->create(['name' => 'Hans']);
263+
$second = Client::query()->create(['name' => 'Thomas']);
264+
265+
$user->load('clients');
266+
self::assertEmpty($user->clients);
267+
268+
$user->clients()->sync($first);
269+
270+
$user->load('clients');
271+
self::assertCount(1, $user->clients);
272+
self::assertTrue($user->clients->first()->is($first));
273+
274+
$user->clients()->sync($second);
275+
276+
$user->load('clients');
277+
self::assertCount(1, $user->clients);
278+
self::assertTrue($user->clients->first()->is($second));
279+
280+
$user->clients()->syncWithoutDetaching($first);
281+
282+
$user->load('clients');
283+
self::assertCount(2, $user->clients);
284+
self::assertTrue($user->clients->first()->is($first));
285+
self::assertTrue($user->clients->last()->is($second));
286+
}
287+
258288
public function testBelongsToManyAttachesExistingModels(): void
259289
{
260290
$user = User::create(['name' => 'John Doe', 'client_ids' => ['1234523']]);

0 commit comments

Comments
 (0)