2013-05-15 49 views
1

我在DataMapper的總初學者,有兩種型號:DataMapper-我可以避免中間表嗎?

class ThirdPartyAccount 
    include DataMapper::Resource 
    property :access_token,  String, :length => 500 
    belongs_to :user 
end 

class User 
    include DataMapper::Resource 
    property :id,   Serial 
    property :first_name, String 
    has n, :third_party_accounts, :through => Resource 
end 

望着SQL日誌,它似乎創建兩個表 - usersthird_party_accountsthird_party_account_users參加這兩項。它看起來並不需要最後一個表 - third_party_account表只需要使用它的user_id字段直接映射到user表?我在這裏意外創建了一個多對多的關係嗎?

回答

1

這是由於該行:

has n, :third_party_accounts, :through => Resource

:through => Resource告訴DataMapper的到,這是一個「具有和-屬於一對多」的關係(每個第三方帳戶屬於多個用戶和每個用戶有多個第三方帳戶),這需要一箇中間表。如果這僅僅是一個具有一對多的關係(每個用戶擁有許多第三方賬戶,但每個只屬於一個用戶帳戶),你應該只使用:

Class User 
    ... 
    has n, :third_party_accounts 
end 

更多信息,請參見http://datamapper.org/docs/associations.html

+0

完美,謝謝。不知道我在哪裏閱讀'''Resource'''的東西 - 儘管我很熟悉SQL和大多數語言,但顯然還是有一些DataMapper需要解析的語義。 – Alastair

相關問題