From 2dda36bf59b70b94e67f2749e0452fa678fa6b1f Mon Sep 17 00:00:00 2001 From: Willian Correa Date: Tue, 27 Aug 2024 18:11:06 -0300 Subject: [PATCH] bugfix: fixes the syncWithType method to avoid deleting tags without a type when mass syncing tags with a type --- src/HasTags.php | 20 +++++++++----------- tests/HasTagsTest.php | 13 +++++++++++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/HasTags.php b/src/HasTags.php index be067f4..fd00f9c 100644 --- a/src/HasTags.php +++ b/src/HasTags.php @@ -260,22 +260,20 @@ protected function syncTagIds($ids, string | null $type = null, $detaching = tru { $isUpdated = false; + $tagModel = $this->tags()->getRelated(); + // Get a list of tag_ids for all current tags $current = $this->tags() ->newPivotStatement() ->where($this->getTaggableMorphName() . '_id', $this->getKey()) ->where($this->getTaggableMorphName() . '_type', $this->getMorphClass()) - ->when($type !== null, function ($query) use ($type) { - $tagModel = $this->tags()->getRelated(); - - return $query->join( - $tagModel->getTable(), - $this->getTaggableTableName() . '.tag_id', - '=', - $tagModel->getTable() . '.' . $tagModel->getKeyName() - ) - ->where($tagModel->getTable() . '.type', $type); - }) + ->join( + $tagModel->getTable(), + 'taggables.tag_id', + '=', + $tagModel->getTable() . '.' . $tagModel->getKeyName() + ) + ->where($tagModel->getTable() . '.type', $type) ->pluck('tag_id') ->all(); diff --git a/tests/HasTagsTest.php b/tests/HasTagsTest.php index a01553c..9971409 100644 --- a/tests/HasTagsTest.php +++ b/tests/HasTagsTest.php @@ -312,6 +312,19 @@ expect($tagsOfTypeB->pluck('name')->toArray())->toEqual(['tagB1', 'tagB2']); }); +it('can sync tags without a type and not affect tags with a type', function () { + $this->testModel->syncTagsWithType(['test1', 'test2'], 'testType'); + + $this->testModel->syncTagsWithType(['test3']); + + expect($this->testModel->tags->pluck('name')->toArray())->toEqual(['test1', 'test2', 'test3']); + + expect($this->testModel->tags->where('name', '=', 'test1')->first()->type)->toEqual('testType'); + + expect($this->testModel->tags->where('name', '=', 'test2')->first()->type)->toEqual('testType'); + + expect($this->testModel->tags->where('name', '=', 'test3')->first()->type)->toBeNull(); +}); it('can sync same tag type with different models with same foreign id', function () { $this->testModel->syncTagsWithType(['tagA1', 'tagA2', 'tagA3'], 'typeA');