Skip to content

Commit

Permalink
Use taggable_type in scopeWithAllTags(*) (#207)
Browse files Browse the repository at this point in the history
scopeWithAllTags and scopeWithAllTagsOfAnyType does not include the taggable_type which leads to wrong results for the given model.

$query = Filter::withAllTagsOfAnyType(['test']);
dd($query->toSql(), $query->getBindings());

*scopeWithAllTags*

Query before change: 
select * from `filters` where `filters`.`id` in (select `taggables`.`taggable_id` from `taggables` where `taggables`.`tag_id` = ?) and `filters`.`deleted_at` is null

Query after change:
select * from `filters` where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` where `filters`.`id` = `taggables`.`taggable_id` and `taggables`.`taggable_type` = ? and `tags`.`id` = ?) and `filters`.`deleted_at` is null

*scopeWithAllTagsOfAnyType*

Query before change:
select * from `filters` where `filters`.`id` in (select `taggables`.`taggable_id` from `taggables` where `taggables`.`tag_id` = ?) and `filters`.`deleted_at` is null

Query after change:
select * from `filters` where exists (select * from `tags` inner join `taggables` on `tags`.`id` = `taggables`.`tag_id` where `filters`.`id` = `taggables`.`taggable_id` and `taggables`.`taggable_type` = ? and `tags`.`id` = ?) and `filters`.`deleted_at` is null
  • Loading branch information
Dewstar authored and freekmurze committed Jul 17, 2019
1 parent 3fa0ab0 commit 4d90c41
Showing 1 changed file with 4 additions and 8 deletions.
12 changes: 4 additions & 8 deletions src/HasTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,8 @@ public function scopeWithAllTags(Builder $query, $tags, string $type = null): Bu
$tags = static::convertToTags($tags, $type);

collect($tags)->each(function ($tag) use ($query) {
$query->whereIn("{$this->getTable()}.{$this->getKeyName()}", function ($query) use ($tag) {
$query->from('taggables')
->select('taggables.taggable_id')
->where('taggables.tag_id', $tag ? $tag->id : 0);
$query->whereHas('tags', function (Builder $query) use ($tag) {
$query->where('tags.id', $tag ? $tag->id : 0);
});
});

Expand Down Expand Up @@ -113,10 +111,8 @@ public function scopeWithAllTagsOfAnyType(Builder $query, $tags): Builder
$tags = static::convertToTagsOfAnyType($tags);

collect($tags)->each(function ($tag) use ($query) {
$query->whereIn("{$this->getTable()}.{$this->getKeyName()}", function ($query) use ($tag) {
$query->from('taggables')
->select('taggables.taggable_id')
->where('taggables.tag_id', $tag ? $tag->id : 0);
$query->whereHas('tags', function (Builder $query) use ($tag) {
$query->where('tags.id', $tag ? $tag->id : 0);
});
});

Expand Down

0 comments on commit 4d90c41

Please sign in to comment.