rinvex / laravel-categories

Rinvex Categorizable is a polymorphic Laravel package, for category management. You can categorize any eloquent model with ease, and utilize the power of Nested Sets, and the awesomeness of Sluggable, and Translatable models out of the box.
MIT License
453 stars 68 forks source link

Get all categories that have a specific model #110

Closed MostafaNorzade closed 2 years ago

MostafaNorzade commented 2 years ago

how to get all categories for a specific model?

Do I have to write it myself?

$categories_id = DB::table('categorizables')
                                ->where('categorizable_type', Blog::class)
                                ->pluck('category_id');

$blog_categories = app('rinvex.categories.category')->whereIn('id', $categories_id)->get();

Is there a method for this?

Omranic commented 2 years ago

Simple, it's a normal Eloquent Polymorphic relationship. Just use:

// Get instance of your model
$blog = new \App\Models\Blog::find();

// Get attached categories collection
$blog->categories;

More details: https://github.com/rinvex/laravel-categories#manage-your-categorizable-model

MostafaNorzade commented 2 years ago

Thanks. but I meant how to get all the categories related to the ‍‍blog. Not how I want to get the categories of a specific blog !!

Omranic commented 2 years ago

I'm not sure how you manager your categories, but how I imagine using this package for a similar use case, I'd create a root category for all blog categories, so I can also use categories for other stuff like products, forums, or whatever. If you've a root category for blog, then it's still easy to get all blog categories $rootBlogCategory->children

I hope that helps, if not, feel free to re-open this issue and explain your use case in more details.

MostafaNorzade commented 2 years ago

Thank. My main need is for when I want to show blog categories in the blog sidebar of the blog or in the sidebar of the store, and I need to list the categories that are used for the products. The method provided by you is not bad either