2012-03-29 85 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 
相关问题