2

我不确定我想做的事情是错误的还是只是我的实施。

我想做的是

在人和地址之间有多个“有 1”关系

我的模型是

class Person
  include DataMapper::Resource

  property id,serial
  property name,String

  has 1, :home, :model => 'Address'
  has 1, :office, :model => 'Address'
  has 1, :mail, :model => 'Address'
end

class Address
 include DataMapper::Resource
 property :id,Serial 
 property addr1, String
 property country, String
end

这在代码中工作正常,我可以分配和访问一个人的国家

a_person.home.country

但是当我保存然后从数据库中退出时它不起作用。它混合了家庭、办公室和邮件地址

我希望得到一个像

CREATE TABLE `addresses` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `addr1` varchar(50) DEFAULT NULL,
  `country` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

CREATE TABLE `persons` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  'home' int(10) unsigned ,
  'office' int(10) unsigned ,
  'mail' int(10) unsigned ,
  PRIMARY KEY (`id`)
) 

我得到的是

CREATE TABLE `addresses` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `addr1` varchar(50) DEFAULT NULL,
  `country` varchar(50) DEFAULT NULL,
  `person_id` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `index_addresses_person` (`person`)
)

CREATE TABLE `persons` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

表结构对我来说并不重要,我想要的是家庭、办公室和邮件都是相同的对象类型,并且最好在同一个表中。如果能够分配相同的 Address 实例来表示 home 和 mail 并且只在地址中存储一次但被引用两次,那就太好了。

PS 人员和地址不是实际的底层对象,它们只是用作熟悉的示例。

编辑:我可以通过将 4 has n assoc 放在地址上来做我想做的事。我将尝试用结果编辑我的答案。

4

1 回答 1

4

实际上你可能想要这样的东西:

class Person
  include DataMapper::Resource

  property :id, Serial
  property :name, String

  belongs_to :home,   :model => Address
  belongs_to :office, :model => Address, :required => false
  belongs_to :mail,   :model => Address, :required => false
end

class Address
  include DataMapper::Resource

  property :id,Serial 
  property :address, String
  property :country, String
end
于 2011-04-20T22:31:54.877 回答