I want two tables, Person and Address, to share their primary key:
CREATE TABLE Person (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);
CREATE TABLE Address (personId INT UNSIGNED NOT NULL PRIMARY KEY);
I'm trying to model the idea that when you create a Person, you're also creating an Address for it.
I came up with the following mapping:
class Person
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
private $id;
/**
* @OneToOne(targetEntity="Address", cascade={"all"})
* @JoinColumn(name="id", referencedColumnName="personId")
*/
private $address;
public function __construct() {
$this->address = new Address($this);
}
}
class Address
{
/**
* @Id
* @OneToOne(targetEntity="Person")
* @JoinColumn(name="personId", referencedColumnName="id")
*/
private $person;
public function __construct(Person $person) {
$this->person = $person;
}
}
When I try to persist Person, I would expect it to cascade to Address, but I get the following exception:
Doctrine\ORM\ORMException
Entity of type
Addresshas identity through a foreign entityPerson, however this entity has no identity itself. You have to callEntityManager#persist()on the related entity and make sure that an identifier was generated before trying to persistAddress. In case of Post Insert ID Generation (such as MySQLAuto-Incrementor PostgreSQLSERIAL) this means you have to callEntityManager#flush()between both persist operations.
I can't explicitly call flush(), because I'm not explicitly persist()ing Address, instead I'm expecting Person to cascade persist Address.
So as far as I understand it, it should be Doctrine's job to flush() at the right moment to get the id.
This one-to-one relationship cascades fine when using different auto_increment ids for both Person and Address (but then I have to add an addressId to Person).
My aim is to make them share the same id.
Is that possible?