diff --git a/src/HasTags.php b/src/HasTags.php index 9c6b879..98950c3 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');