Skip to content

Commit

Permalink
Merge pull request #511 from stanbridge-wcorrea/main
Browse files Browse the repository at this point in the history
bugfix: fixes the syncWithType method to avoid deleting tags without …
  • Loading branch information
AlexVanderbist authored Oct 3, 2024
2 parents 713f0bb + 4dfe721 commit 1e6d647
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/HasTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand Down
13 changes: 13 additions & 0 deletions tests/HasTagsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down

0 comments on commit 1e6d647

Please sign in to comment.