-
-
Notifications
You must be signed in to change notification settings - Fork 290
Description
Context
I have a need to use spatie/laravel-tags with table names prefixed by 'api_'. I have created custom Tag model and configured table_name
`use Spatie\Tags\Tag as BaseTags;
class Tag extends BaseTags
{
protected $table = 'api_tags';
}
I have configured config/tags.php to use my model, and use different taggable table_name: api_taggable. Most of functions worked as intended, by i hade problems invoking query: $query->withAllTags(["tags"]); `
It turned out that scopeWithAllTags is using static tags.id condition:
` public function scopeWithAllTags(
Builder $query,
string | array | ArrayAccess | Tag $tags,
string $type = null,
): Builder {
$tags = static::convertToTags($tags, $type);
collect($tags)->each(function ($tag) use ($query) {
$query->whereHas('tags', function (Builder $query) use ($tag) {
**$query->where('tags.id', $tag->id ?? 0);**
});
});
return $query;
}
`
Exception
It caused exception:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tags.id' in 'where clause'
Solution
I think the solution is to use configured tags table name as given below:
`
public function scopeWithAllTags(
Builder $query,
string|array|ArrayAccess|Tag $tags,
?string $type = null,
): Builder {
$tags = static::convertToTags($tags, $type);
collect($tags)->each(function ($tag) use ($query) {
$query->whereHas('tags', function (Builder $query) use ($tag) {
$query->where($this->getTagsTablePrimaryKey(), $tag->id ?? 0);
});
});
return $query;
}
protected function getTagsTablePrimaryKey(): string
{
return $this->tags()->getRelated()->getTable().'.id';
}
`