Description
If you have an Entity like this:
/**
* @ORM\Entity
* @ORM\Table(name="takedown")
*/
class Takedown {
/**
* @var int
*
* @ORM\Column(name="takedown_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue
*/
private $id;
/**
* @var DigitalMillenniumCopyrightAct
*
* @ORM\OneToOne(targetEntity="DigitalMillenniumCopyrightAct", mappedBy="takedown", orphanRemoval=true, cascade={"persist"})
*/
private $dmca;
public function setDmca( $dmca = null ) : self {
if ( $dmca === null ) {
$this->dmca = null;
return $this;
}
$this->dmca = $dmca;
$this->dmca->setTakedown( $this );
return $this;
}
public function getDmca() :? DigitalMillenniumCopyrightAct {
return $this->dmca;
}
}
and the related entity:
/**
* @ORM\Entity
* @ORM\Table(name="takedown_dmca")
*/
class DigitalMillenniumCopyrightAct {
/**
* @ORM\Id
* @ORM\OneToOne(
* targetEntity="Takedown",
* inversedBy="dmca"
*)
* @ORM\JoinColumn(name="takedown_id", referencedColumnName="takedown_id")
*/
private $takedown;
public function setTakedown( Takedown $takedown ) : self {
$this->takedown = $takedown;
return $this;
}
public function getTakedown( ) :? Takedown {
return $this->takedown;
}
}
Doing something like this:
$takedown = new Takedown();
$takedown->setDmca(new DigitalMillenniumCopyrightAct());
$em->persist($takedown);
$em->flush();
will always fail with an error:
The given entity of type 'DigitalMillenniumCopyrightAct' (DigitalMillenniumCopyrightAct@000000000c1a46f70000000005683920) has no identity/no id values set. It cannot be added to the identity map.
I've also tried explicit persisting:
$takedown = new Takedown();
$takedown->setDmca(new DigitalMillenniumCopyrightAct());
$em->persist($takedown);
$em->persist($takedown->getDmca());
$em->flush();
But also fails with the same error.
The only work-around I have found is to remove the related entity completely, then persist & flush and then persist the related entity:
$takedown = new Takedown();
$takedown->setDmca(new DigitalMillenniumCopyrightAct());
$dmca = $takedown->getDmca();
$takedown->setDmca();
$em->persist($takedown);
$em->flush();
$takedown->setDmca($dmca);
$em->persist($takedown->getDmca());
$em->flush():
Is there a way to do this without removing the related entities, flushing, and then persisting the related entities afterwards? I think it would be a lot easier if it was possible, if not, is there some way to make it part of the same transaction? (so if the related entity fails persisting, the initial one will be rolled back?)