Skip to content

Commit 4065ab7

Browse files
authored
[12.x] Return early on belongs-to-many relationship syncWithoutDetaching method when empty values are given (#56157)
* Prevent unnecessary sync when IDs are empty and detaching is false * Add test for sync with empty array and detaching disabled * Test with all empty values * Rearrange precedence of methods * Tweak test * Disable query log after sync test
1 parent a9547c8 commit 4065ab7

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivotTable.php

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,18 @@ public function sync($ids, $detaching = true)
8787
'attached' => [], 'detached' => [], 'updated' => [],
8888
];
8989

90+
$records = $this->formatRecordsList($this->parseIds($ids));
91+
92+
if (empty($records) && ! $detaching) {
93+
return $changes;
94+
}
95+
9096
// First we need to attach any of the associated models that are not currently
9197
// in this joining table. We'll spin through the given IDs, checking to see
9298
// if they exist in the array of current ones, and if not we will insert.
9399
$current = $this->getCurrentlyAttachedPivots()
94100
->pluck($this->relatedPivotKey)->all();
95101

96-
$records = $this->formatRecordsList($this->parseIds($ids));
97-
98102
// Next, we will take the differences of the currents and given IDs and detach
99103
// all of the entities that exist in the "current" array but are not in the
100104
// array of the new IDs given to the method which will complete the sync.

tests/Integration/Database/EloquentBelongsToManyTest.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -909,6 +909,27 @@ public function testSyncWithoutDetachingMethod()
909909
);
910910
}
911911

912+
public function testSyncMethodWithEmptyValueDoesNotQueryWhenDetachingDisabled()
913+
{
914+
$post = Post::create(['title' => Str::random()]);
915+
916+
DB::enableQueryLog();
917+
918+
foreach ([collect(), [], null] as $value) {
919+
$result = $post->tags()->sync($value, false);
920+
921+
$this->assertEquals([
922+
'attached' => [],
923+
'detached' => [],
924+
'updated' => [],
925+
], $result);
926+
}
927+
928+
$this->assertEmpty(DB::getQueryLog());
929+
930+
DB::disableQueryLog();
931+
}
932+
912933
public function testToggleMethod()
913934
{
914935
$post = Post::create(['title' => Str::random()]);

0 commit comments

Comments
 (0)