【问题标题】:How do I handle complex relations with Laravel?如何处理与 Laravel 的复杂关系?
【发布时间】:2021-10-07 00:31:32
【问题描述】:

虽然非常感谢基于代码的答案,但我有兴趣了解处理此问题背后的逻辑,因为以后可能会再次发生。

我正在做一个电子商务项目。大多数产品都是变量。例如想象一件衬衫。

一件衬衫可以有 5 种不同的尺码(XS、S、M、ML、L)和 3 种颜色(红、绿、蓝)。这些是示例,这些属性是动态的,可以随时编辑。我的方法是为产品本身创建 3 个不同的表:

- main_product_table
    - id

- product_variant_table
    - id
    - main_product_id

- product_variant_combination_table
    - id
    - variant_id
    - attribute_name_id
    - attribute_value_id

还有 2 个属性表:

- attribute_name_table
    - id
    - attribute_name

- attribute_value_table
    - id
    - attribute_value

因此,例如,上述衬衫现在将创建以下记录:

  • attribute_name_table 中有 2 条记录
  • attribute_value_table 中有 3 条记录
  • main_product_table 中有 1 条记录
  • product_variant_table 中的 3x5 条记录
  • product_variant_combination_table 中的 2x3x5 条记录(2 行,每行包含 1 个属性的值)

现在考虑查询所有包含 XS 尺寸的产品,或查询该产品及其所有变体数据。

我的问题是:

  1. 雄辩的模型可以处理这个问题吗?
  2. 如果是这样,我应该创建 5 个模型,每个表 1 个吗?
  3. 如果不是,我应该创建一个(或 2 个)模型(产品、属性)并使用自定义 SQL 和方法连接它们吗?
  4. 这里有什么关系?属性对我来说似乎是一对多的,但组合似乎也是一对多的,而且这两者也相互关联。

我很难理解上述之间的关系。通过 SQL 似乎可以理解,但我无法通过 Eloquents 将它们相互关联。

此外,表格似乎迅速增长。这种方法是否正确?

【问题讨论】:

    标签: laravel eloquent orm


    【解决方案1】:

    从长远来看,您的方法似乎很难维持。我不明白您为什么必须将 name 属性与 value 分开。

    我将创建产品型号、尺寸和颜色及其迁移和数据透视表来存储库存

    - size_table
    -- id
    -- name
    
    - color_table
    -- id
    -- name
    
    - product_table
    -- id
    -- type (shirt, pants, pullover ... etc.)
    -- description
    -- status
    
    - stock_table
    -- product_id (reference to the product table)
    -- color_id (Reference to the color table)
    -- size_id (Reference to the size table)
    -- quantity (Quantity of products available with these attributes)
    -- status
    

    这样您就可以在 stock_table 中存储多个组合的相同产品。

    现在您只需要定义每个模型之间的关系,然后您就可以访问 product_detail_table 中的所有属性

    $item->quantity
    $item->product->description
    $item->size->name
    $item->color->name
    

    【讨论】:

    • 谢谢,但不幸的是,这个答案没有帮助。尺寸和颜色只是示例。属性是动态的,它们不能绑定到列。此外,它们的值是分开的以保持标准化。否则你最终会得到大量重复数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 2020-01-12
    • 1970-01-01
    • 2022-01-06
    • 2018-02-02
    相关资源
    最近更新 更多