Laravel 和 mysql table 类别的命名约定

Laravel and mysql table name conventions for categories

我在 laravel 中遇到 mysql 的 table 的名称约定问题,特别是类别名称。

我发现有很多类似类别的 table 来标识模型类别。 在某些情况下,我设法重命名它们,避免使用前缀 'category'。例如,模型 UserCategory 已成为角色,table 已成为角色。有了这个技巧,我可以有一个可读的 role_user pivot table.

在其他情况下,我找不到合适的名称:ProductCategory、CarCategory、StyleCategory 等等。在这种情况下最好的方法是什么?我可以为模型和 table 分配什么最佳名称?

此外,如果一个模型有多个他类型的类别,我应该有类似 product_productcategory pivot table 的东西,那太糟糕了。这就是为什么我总是喜欢避免在 model/table 中使用类别这个词,但恐怕在这些情况下没有其他方法。

你的方法是什么?有一些最佳实践吗?

如果您的类别表有共同的列,我建议使用 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

ProductCar 模型都将有一个 categories 方法调用基础 Eloquent class 的 morphToMany 方法:

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

反向关系:

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