【问题标题】:Laravel and mysql table name conventions for categories类别的 Laravel 和 mysql 表名约定
【发布时间】:2020-06-13 08:35:05
【问题描述】:

我在 laravel 中遇到了 mysql 表的命名约定问题,尤其是类别名称。

我发现有很多类似类别的表格来识别模型类别。 在某些情况下,我设法重命名它们,避免使用前缀“类别”。例如模型 UserCategory 变成了 Role,表变成了角色。通过这个技巧,我可以获得一个可读的 role_user 数据透视表。

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

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

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

【问题讨论】:

  • 尝试使用多态关系。查看文档here

标签: mysql database laravel model naming-conventions


【解决方案1】:

如果您的类别表有共同的列,我建议使用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 基类上调用 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');
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 2014-11-13
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多