我需要将一些不可变字段移动到单独的类中,但我真的不想使用“join”,因为我每次都需要所有数据。
是否可以将某些实体属性作为映射到同一个表的类?
类似的东西:
/**
* @ORM\Entity
*/
class User {
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...
/**
* @var Address
* @ORM\... ??
*/
protected $address
}
/**
* @ORM\ValueObject ??
*/
class Address {
/**
* @var string
* @ORM\Column(type="string", name="address_zipcode", length=12)
*/
protected $zipcode;
/**
* @var string
* @ORM\Column(type="string", name="address_country_iso", length=3)
*/
protected $countryIso;
...
}
表格结构如下:
CREATE TABLE User (
`id` INT(11) NOT NULL auto_increment,
`address_zipcode` VARCHAR(12) NOT NULL,
`address_country_iso` VARCHAR(3) NOT NULL,
PRIMARY KEY (`id`)
);
答案 0 :(得分:1)
您所询问的内容称为“价值对象”。
Jira DDC-93中存在一个未解决的问题,需要添加支持。它目前在版本2.5中标记为已解决,该版本刚刚在Beta版本中发布。
答案 1 :(得分:0)
如果您在没有加入的情况下存储对象:
/**
* @ORM\Column(name="adress", type="object")
*/
它会自动序列化/反序列化为文本字段
http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/types.html
添加你想要存储的类型的setter
public function setAdress(Address $adress)
{
$this->adress = $adress;
return $this;
}
地址类不需要任何@ORM注释
答案 2 :(得分:0)
就像你说的那样。
将@PreUpdate和@PostLoad挂钩添加到User
。
/**
* @ORM\Entity
*/
class User {
/**
* @var int
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
...
/**
* @var Address
* (NOTE: no @ORM annotation here)
*/
protected $address
/**
* @var string
* @ORM\Column(type="string")
*/
protected $addressZipCode;
/**
* @var string
* @ORM\Column(type="string")
*/
protected $addressCountryIso;
public function setAddress(Address $address)
{
$this->address = $address;
}
/**
* @ORM\PreUpdate
*
* set $addressZipCode and $addressCountryInfo when this object is to
* save so that doctrine can easily save these scalar values
*/
public function extractAddress()
{
$this->addressZipCode = $this->address->getZipCode();
$this->addressCountryIso = $this->address->getAddressCountryIso();
}
/**
* @ORM\PostLoad
*
* When the row is hydrated into this class,
* $address is not set because that isn't mapped.
* so simply, map it manually
*/
public function packAddress()
{
$this->address = new Address();
$this->address->setZipCode($this->addressZipCode);
$this->address->setCountryIs($this->addressCountryIso);
}
}