rtconner / laravel-tagging

Tag support for Laravel Eloquent models - Taggable Trait
MIT License
882 stars 168 forks source link

Get all tags by type #16

Closed mikelmi closed 9 years ago

mikelmi commented 10 years ago

How I can get all tags filterd by type (related model)?

rtconner commented 10 years ago

Don't seem to have a function that does that. Would probably need to look something like "Find distinct from Tagged where taggable_type = 'MyModel'"

If you write one please contribute back into the repository.

blackfyre commented 9 years ago

:+1:

jonascarlbaum commented 9 years ago

I implemented this in my model class (I only use this tagging in one model for now), but it might be something to add to the trait to be able to call Model::tagList() on each taggable model?

    public static function tagList()
    {
        return implode(',', \DB::table('tagging_tagged')
            ->distinct()
            ->where('tagging_tagged.taggable_type', 'like', get_called_class())
            ->orderBy('tagging_tagged.tag_slug')
            ->lists('tagging_tagged.tag_slug'));
    }

Or why not implement the a tag array getter first:

    public static function tagArray()
    {
        return \DB::table('tagging_tagged')
            ->distinct()
            ->where('tagging_tagged.taggable_type', 'like', get_called_class())
            ->orderBy('tagging_tagged.tag_slug')
            ->lists('tagging_tagged.tag_slug');
    }

And use the tag array getter to provide a list as comma-separated string:

    public static function tagList()
    {
        return implode(',', static::tagArray());
    }

Or you might do this using scope or something...

However, I needed this and is currently satisfied with the method I implemented for my current needs, but if implemented in the trait if would be great... ;)

Tried to copy the methods as they are into TaggableTrait and it works as expected when accessed as previously => Model::tagList()...

Update: joining with taggable_tags creates a smaller subset and makes it faster when having lots of tags for lots of instances, so this is (in my case) a solution with better performance:

    public static function tagArray()
    {
        return \DB::table('tagging_tagged')
            ->distinct()
            ->join('tagging_tags', 'tagging_tagged.tag_slug', '=', 'tagging_tags.slug')
            ->where('tagging_tagged.taggable_type', 'like', get_called_class())
            ->orderBy('tagging_tags.slug')
            ->lists('tagging_tags.slug');
    }