如何使用DataMapper在相同模型之间设置has n, :through => Resource
类型的多个关系?
例如,在新闻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
然而,这不起作用。数据库只有一个关系表,其中必须为每个关系指定作者和编辑器,这甚至没有意义。
我该怎么办?
答案 0 :(得分: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