Doctrine ORM 2.5将可嵌入的内容添加到类as explained here中。我想知道以下是否可行,如果可行,如何。
<?php
/** @Entity */
class User
{
/** @Embedded(class = "Address") */
private $address;
}
/** @Embeddable */
class Address
{
/** @Column(type = "string") */
private $street;
...
/**
* @ManyToOne(targetEntity="City")
* @JoinColumn(name="city_id", referencedColumnName="id")
**/
private $city;
}
/** @Entity */
class City
{
...
}
我认为,由于Address
和User
是同一个表的一部分,City
应该在数据库中保存对User
的引用。但我不确定这是否可行。任何帮助将不胜感激。
答案 0 :(得分:2)
正如教程所述:
就数据库架构而言,Doctrine会自动将Address类中的所有列内联到User类的表中,就像您直接在那里声明它们一样。
生成的唯一表格是User
和City
。 Address
的信息直接合并到User
表中。对于您的测试用例,这会产生以下SQL:
CREATE TABLE User (id INT AUTO_INCREMENT NOT NULL, address_street VARCHAR(255) NOT NULL, address_postalCode VARCHAR(255) NOT NULL, address_country VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE City (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
正如您所看到的,与City的关系完全缺失,因为此功能目前尚未实现(尚未实现)。现在你需要保持关系不受嵌入:
<?php
/** @Entity */
class User {
/**
* @Column(type="integer")
* @GeneratedValue
* @Id()
*/
protected $id;
/** @Embedded(class = "Address") */
private $address;
/** @ManyToOne(targetEntity="City") */
private $city;
}
这会生成您可能期望的表格,包括与城市的关系:
CREATE TABLE User (id INT AUTO_INCREMENT NOT NULL, city_id INT DEFAULT NULL, address_street VARCHAR(255) NOT NULL, address_postalCode VARCHAR(255) NOT NULL, address_country VARCHAR(255) NOT NULL, INDEX IDX_E0C1DE1C8BAC62AF (city_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
CREATE TABLE City (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB;
ALTER TABLE User ADD CONSTRAINT FK_E0C1DE1C8BAC62AF FOREIGN KEY (city_id) REFERENCES City (id);
我建议您发布到doctrine-user mailing list,他们对similar questions反应灵敏。