【问题标题】:DataMapper has_one problemDataMapper has_one 问题
【发布时间】:2009-07-05 07:35:46
【问题描述】:

我在 DataMapper 中关联模型时遇到问题。它真的很简单,但我能明白。

所以,我有 2 张桌子:

1. Books
-> id
-> title
-> publisher_id

2. Publishers
-> id
-> title

类:

class Book
  property :id, Serial
  property :title, String
  property :publisher_id, Integer
end

class Publisher
  property :id, Serial
  property :title, String
end

所以,问题是:如何将出版商连接到图书?这是一对一的关系,整个事情应该是这样的:

p = Book.get(12345).publisher

对不起,也许这是愚蠢的。但我只是不知道我应该使用什么样的声明。

【问题讨论】:

    标签: ruby datamapper one-to-one


    【解决方案1】:

    哈哈,我是凌晨 2 点的傻白痴。总是发生在我身上,当我问这个问题时 - 突然自己为我的问题找到答案。

    不正确,是一对多的关系。所以,它就像天空中的太阳一样简单:

    class Book
      property :id, Serial
      property :title, String
      property :publisher_id, Integer
    
      belongs_to :publisher
    end
    
    class Publisher
      property :id, Serial
      property :title, String
    
      has n, :books
    end
    

    就是这样。这可能对某人有帮助。

    【讨论】:

    • 在 ActiveRecord 和 DataMapper 中,具有外键的表由具有 belongs_to 关联的类表示;关系的另一端由某种形式的“有”关联表示。在 ActiveRecord 中,这可以是“has_one”或“has_many”;在 DataMapper 中,"has (arity)",其中 arity 可以是任意数字(即有 1)、范围(有 2..4)或无穷大(有 n)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多