diff --git a/app/Harvest/Importers/GmuhkItemImporter.php b/app/Harvest/Importers/GmuhkItemImporter.php index 91909ffcf..a15c56dc7 100644 --- a/app/Harvest/Importers/GmuhkItemImporter.php +++ b/app/Harvest/Importers/GmuhkItemImporter.php @@ -45,11 +45,14 @@ public function import(array $row, Progress $result) { return $authorities->count() === 1; }) ->map->first() - ->mapWithKeys( - fn(Authority $authority, $author) => [ - $authority->id => ['role' => AuthorityMatcher::parse($author)['alt_name']], - ] - ); + ->mapWithKeys(function(Authority $authority, $author) { + $pivotData = []; + if ($role = AuthorityMatcher::parse($author)['alt_name']) { + $pivotData['role'] = $role; + } + + return [$authority->id => $pivotData]; + }); $item->syncMatchedAuthorities($matches); diff --git a/app/Item.php b/app/Item.php index 60361409e..7a847b3c4 100644 --- a/app/Item.php +++ b/app/Item.php @@ -790,7 +790,9 @@ public function syncMatchedAuthorities(\Illuminate\Support\Collection|array $ids // Update existing pivot data foreach ($idsWithPivotData as $id => $pivotData) { - $this->authorities()->updateExistingPivot($id, $pivotData); + if ($pivotData) { + $this->authorities()->updateExistingPivot($id, $pivotData); + } } // Create new authorities diff --git a/tests/Models/ItemTest.php b/tests/Models/ItemTest.php index b129d0569..d18526824 100644 --- a/tests/Models/ItemTest.php +++ b/tests/Models/ItemTest.php @@ -258,4 +258,40 @@ public function testSyncMatchedAuthoritiesAddsNew() 'automatically_matched' => true, ]); } + + public function testSyncMatchedAuthoritiesCreatesWithoutPivotData() + { + $item = Item::factory()->create(); + $authority = Authority::factory()->create(); + + $item->syncMatchedAuthorities([ + $authority->id => [], + ]); + + $this->assertDatabaseHas('authority_item', [ + 'authority_id' => $authority->id, + 'item_id' => $item->id, + 'role' => null, + 'automatically_matched' => true, + ]); + } + + public function testSyncMatchedAuthoritiesUpdatesWithoutPivotData() + { + $item = Item::factory()->create(); + $authority = Authority::factory()->create(); + $item->authorities()->sync([ + $authority->id => ['role' => 'author'], + ]); + + $item->syncMatchedAuthorities([ + $authority->id => [], + ]); + + $this->assertDatabaseHas('authority_item', [ + 'authority_id' => $authority->id, + 'item_id' => $item->id, + 'role' => 'author', + ]); + } }