Skip to content

Commit 1e6d647

Browse files
Merge pull request #511 from stanbridge-wcorrea/main
bugfix: fixes the syncWithType method to avoid deleting tags without …
2 parents 713f0bb + 4dfe721 commit 1e6d647

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

src/HasTags.php

+9-11
Original file line numberDiff line numberDiff line change
@@ -260,22 +260,20 @@ protected function syncTagIds($ids, string | null $type = null, $detaching = tru
260260
{
261261
$isUpdated = false;
262262

263+
$tagModel = $this->tags()->getRelated();
264+
263265
// Get a list of tag_ids for all current tags
264266
$current = $this->tags()
265267
->newPivotStatement()
266268
->where($this->getTaggableMorphName() . '_id', $this->getKey())
267269
->where($this->getTaggableMorphName() . '_type', $this->getMorphClass())
268-
->when($type !== null, function ($query) use ($type) {
269-
$tagModel = $this->tags()->getRelated();
270-
271-
return $query->join(
272-
$tagModel->getTable(),
273-
$this->getTaggableTableName() . '.tag_id',
274-
'=',
275-
$tagModel->getTable() . '.' . $tagModel->getKeyName()
276-
)
277-
->where($tagModel->getTable() . '.type', $type);
278-
})
270+
->join(
271+
$tagModel->getTable(),
272+
'taggables.tag_id',
273+
'=',
274+
$tagModel->getTable() . '.' . $tagModel->getKeyName()
275+
)
276+
->where($tagModel->getTable() . '.type', $type)
279277
->pluck('tag_id')
280278
->all();
281279

tests/HasTagsTest.php

+13
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,19 @@
312312
expect($tagsOfTypeB->pluck('name')->toArray())->toEqual(['tagB1', 'tagB2']);
313313
});
314314

315+
it('can sync tags without a type and not affect tags with a type', function () {
316+
$this->testModel->syncTagsWithType(['test1', 'test2'], 'testType');
317+
318+
$this->testModel->syncTagsWithType(['test3']);
319+
320+
expect($this->testModel->tags->pluck('name')->toArray())->toEqual(['test1', 'test2', 'test3']);
321+
322+
expect($this->testModel->tags->where('name', '=', 'test1')->first()->type)->toEqual('testType');
323+
324+
expect($this->testModel->tags->where('name', '=', 'test2')->first()->type)->toEqual('testType');
325+
326+
expect($this->testModel->tags->where('name', '=', 'test3')->first()->type)->toBeNull();
327+
});
315328

316329
it('can sync same tag type with different models with same foreign id', function () {
317330
$this->testModel->syncTagsWithType(['tagA1', 'tagA2', 'tagA3'], 'typeA');

0 commit comments

Comments
 (0)