Skip to content

Problem with using custom tag model or custom Tag table name #494

@kamil-stellis

Description

@kamil-stellis

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';
}

`

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions