2012-03-29 42 views
1

如何使用DataMapper在相同模型之間設置has n, :through => Resource類型的多個關係?DataMapper:多個在同一模型之間具有 - 屬於多個關係?

例如,在一個新聞CMS我想有這樣的事情:

class User 
    include DataMapper::Resource 

    has n, :written_articles, 'Article', :through => Resource 
    has n, :edited_articles, 'Article', :through => Resource 

    property :name, String # etc. 
end 

class Article 
    include DataMapper::Resource 

    has n, :authors, 'User', :through => Resource 
    has n, :editors, 'User', :through => Resource 

    property :title, String # etc. 
end 

但是,這是行不通的。數據庫只有一個關係表,其中必須爲每個關係指定作者和編輯者,這甚至沒有意義。

我該怎麼做這樣的事情?

回答

1

您無法使用匿名資源來完成它 - 您提供的代碼將創建單個關係模型UserArticle,它無法處理兩個多對多關係(至少是自動)。您需要創建一個單獨的顯式關係模型,例如ArticleEditor來處理這個問題。

class ArticleEditor 
    include DataMapper::Resource 

    belongs_to :article, :key => true 
    belongs_to :user, :key => true 
end 

,並在你的模型狀態

has n, :article_editors 
has n, :editors (or :edited_articles), :through => :article_editors 
相關問題