我如何处理与 Laravel 的复杂关系?

虽然非常感谢基于代码的答案,但我很想知道处理这个问题背后的逻辑,因为它可能会在以后再次发生。

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

一件衬衫可以有 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. 如果不是,我应该创建一个(或两个)模型(产品、属性)并使用自定义 SQL 和方法连接它们吗?
  4. 这里有什么关系?属性对我来说似乎是一对多的,但组合也似乎是一对多的,而且这两者也是相互关联的。

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

此外,表格似乎迅速增长。这种方法完全正确吗?

hftxc 回答:我如何处理与 Laravel 的复杂关系?

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

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

- 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
本文链接:https://www.f2er.com/2990.html

大家都在问