In Symfony 3 with Doctrine I'm trying to get a one-to-one unidirectional relationship with both tables sharing the same primary key working. To do so I'm trying to replicate the example on the Doctrine Association Mapping page.
However, the one-to-one uni documentation has no examples of setters and getters - and there is no definition of the id field on the target entity, either. So I tried to experiment around myself.
These are my entities:
class Country
{
/**
* @var integer
*
* @ORMColumn(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* @ORMOneToOne(targetEntity="MySubEntity", cascade={"persist", "remove"})
* @ORMJoinColumn(name="id", referencedColumnName="id", nullable=true)
*/
private $mysubentity;
[...]
/**
* @return MySubEntity
*/
public function getMySubEntity()
{
return $this->mysubentity;
}
/**
* @param MySubEntity $mysubentity
*/
public function setMySubEntity($mysubentity)
{
$this->mysubentity = $mysubentity;
}
}
class MySubEntity
{
/**
* @var integer
*
* @ORMColumn(name="id", type="integer", precision=0, scale=0, nullable=false, unique=false)
* @ORMId
* @ORMGeneratedValue(strategy="IDENTITY")
*/
private $id;
[..]
/**
* Set id
*
* @param $id
*
* @return MySubEntity
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
}
When I persist the country entity, I receive Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
. When inspecting the data I can see that Doctrine attempted to set the id of MySubEntity to 0.
Does anybody have an idea what I need to do for the MySubEntity $id field to be auto-populated from the Country entity?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…