【问题标题】:How should I architect a reviews model for reviewing products by a user using mongoDB/mongoid?我应该如何构建一个评论模型来让用户使用 mongoDB/mongoid 来评论产品?
【发布时间】:2012-11-20 14:52:54
【问题描述】:

我对 mongodb/mongoid 非常陌生,并且想知道构建一个使用户能够审查产品的系统的最佳方法。 User 和 Product 将是单独的集合。但是他们都需要访问 Review 模型来显示他们在用户和产品页面上所做的评论。我应该使用嵌入的 1(用户)- 1(评论)关系创建链接的 1(产品)-N(评论)关系吗?这是正确的方法吗?

用户模型

class User
  include Mongoid::Document

  field :name, type: String
  field :email, type: String

  embeds_many :reviews, cascade_callbacks: true
end

产品型号

class Product
  include Mongoid::Document

  field :name, type: String
  field :price, type: Float

  has_many :reviews, dependent: :destroy
end

审查模型

class Review
  include Mongoid::Document

  field :rating, type: Integer

  belongs_to :product
  embedded_in :user
end

谢谢

【问题讨论】:

    标签: mongodb mongoid


    【解决方案1】:

    这不是定义模型结构的正确方法,因为您无法直接访问嵌入式文档,并且您将无法在产品和评论之间创建引用关系。正确的结构是

    用户模型

    class User
      include Mongoid::Document
    
      field :name, type: String
      field :email, type: String
    
      has_many :reviews, dependent: :destroy
    end
    

    产品型号

    class Product
      include Mongoid::Document
    
      field :name, type: String
      field :price, type: Float
    
      has_many :reviews, dependent: :destroy
    end
    

    审查模型

    class Review
      include Mongoid::Document
    
      field :rating, type: Integer
    
      belongs_to :product
      belongs_to :user
    end
    

    【讨论】:

    • 这会不会很慢,因为每次访问数据时都需要进行联接?
    • 是的,它与嵌入关系相比,但您需要用户和产品的数据来进行评论......它会使嵌入的查询更快,但另一个查询真的很混乱和时间服用。当我们将评论嵌入到帖子中时,我们通常在帖子和评论结构中面临同样的问题,当您必须找出用户创建的 cmets 时,查询速度非常慢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 2019-01-22
    相关资源
    最近更新 更多