【问题标题】:Rails - Data model complex relationship between entitiesRails - 数据模型实体之间的复杂关系
【发布时间】:2014-01-31 17:04:57
【问题描述】:

我正在用 Rails 编写一个软件。模型之间的两种关系让我对属性应该驻留在哪里感到头疼。这是一种非典型定价方案,涉及出售给某些客户的产品价格。我们的产品可能会根据客户以不同的价格出售。我们出售的一些较大的公司已经将我们的价格降低了一点。

General Pricing Applicable to most customers
  Product A -> $50
  Product B -> $60
  Product C -> $70

因此,在这种情况下,很容易说产品具有价格属性。但是,该公司已与一些大客户协商价格,可能会出现以下情况。

ACME Corporation
  Product A -> $45
  Product B -> $56
  Product C -> $64

ABC Incorporated
  Product A -> $43
  Product B -> $55
  Product C -> $66

这些价​​格是协商的,而不是基于原始价格的某个折扣百分比。这引入了一个问题,即每个产品可以根据客户有多个价格。我该如何建模。在大多数用例下,以下工作。

Customer has_many :quotes
Quote belongs_to :customer

Quote has_many :quote_items
QuoteItem belongs_to :quote

Product has_many :quote_items
QuoteItem belongs_to :product

但是由于产品的价格可能因客户而异,所以这是如何建模的?例如,产品与客户之间是否存在多对多关系?

【问题讨论】:

    标签: ruby-on-rails database-design model


    【解决方案1】:

    不确定基础架构是如何布局的,但这里有一个想法。

    Customer has_many :products
    Product belongs_to :customer
    

    然后只需转到 Product 模型并创建一个“quote”属性。

    那么你可以做例如

    ACME.ProductA.quote
    => $45
    

    编辑(添加更多)

    嗯,你必须详细说明......事实上,如果你想获得库存 - 比如说 - productA 的所有实例,只需执行类似(概念上)的操作

    listOfProducts = Product.find_by_<name>("productA") 
    
    for each productA from listOfProducts 
      print productA.quote 
    

    如果您想进一步获取产品的客户,可以通过URL解析来跟踪客户的ID

    【讨论】:

    • 这个想法会产生很多重复记录。如果将来我想跟踪库存,我可能为同一产品有 5 个单独的表条目。产品应该在产品表中有一条记录。
    • 我假设每个客户的每个产品都有一个独特的价格。
    • 这不是他们的产品。是我们的产品为每个客户定价不同。产品 A 可能以 55 美元的价格卖给客户 A,客户 B 的价格为 45 美元。
    • 嗯,你必须详细说明......事实上,如果你想获得库存 - 比如说 - productA 的所有实例,只需执行类似(概念上)listOfProducts = Product.find_by_("productA") for each productA from listOfProducts print productA.quote 如果您想进一步获取该产品的客户,您可以通过 URL 解析跟踪客户的 ID
    • 您的答案充其量只是黑客行为。展示。如果一个产品有 20 个属性,你的解决方案是为每个我有不同定价的客户复制其中的 19 个。如果我有 20 个客户,我必须输入 380 个属性。唯一需要额外跟踪的数据是价格属性。每次我为我的一个低利润高收入客户协商非标准价格时,输入描述、名称、项目代码等似乎是一种浪费。这就是我所说的重复。
    【解决方案2】:

    我想出的解决方案是产品和客户之间的多对多关系,并利用名为 product_customers 的查找表来跟踪价格属性。不确定这是否是最优雅的方法,但它可以最大限度地减少重复。缺点是处理表格的额外复杂性。如果有人提出更优雅的答案,我会给他们加分。

    Customer has_many :products, :through => :customer_products
    Customer has_many :customer_products
    Customer has_many :quotes
    Quote belongs_to :customer
    
    Product has_many :customers, :through => :customer_products
    Product has_many :customer_products
    Product has_many :quote_items
    QuoteItem belongs_to :product
    
    CustomerProducts belongs_to :customers
    CustomerProducts belongs_to :products
    
    Quote has_many :quote_items
    QuoteItem belongs_to :quote
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      相关资源
      最近更新 更多