Ad

Laravel And Mysql Table Name Conventions For Categories

I'm facing a problem with name conventions for mysql's tables in laravel, expecially for categories name.

I found out to have a lot of category-like tables to identify a Model category. In some cases I managed to rename them avoiding the prefix 'category'. For example the model UserCategory has become Role, and the table has become roles. With this trick I can have a readable role_user pivot table.

In other cases I can't find a proper name: ProductCategory, CarCategory, StyleCategory and so on. What is the best approach in this case? And what is the best name could I assign to the model and to the table?

Furthermore, if a model has multiple categories of his type I should have something like product_productcategory pivot table and that's orrible. That's why I always prefer to avoid the word category in a model/table, but I'm afraid there are no other ways in these cases.

What is your approach? Are there some best practices?

Ad

Answer

If your category tables have columns in common, I would suggest using many-to-many polymorphic relation:

product
    id - integer
    name- string

car
    id - integer
    manufacturer - string
    model - string

categories
    id - integer
    name - string

categorizable
    category_id - integer
    categorizable_id - integer
    categorizable_type - string

The Product and Car models will both have a categories method that calls the morphToMany method on the base Eloquent class:

class Product extends Model
{
    /**
     * Get all of the categories for the product.
     */
    public function categories()
    {
        return $this->morphToMany('App\Category', 'categorizable');
    }
}

Inverse of the relationship:

class Category extends Model
{
    /**
     * Get all of the products that are assigned this category.
     */
    public function products()
    {
        return $this->morphedByMany('App\Product', 'categorizable');
    }

    /**
     * Get all of the cars that are assigned this category.
     */
    public function cars()
    {
        return $this->morphedByMany('App\Video', 'categorizable');
    }
}
Ad
source: stackoverflow.com
Ad