我有两个实体:
在每个基因座上,我们可以定义许多不同的参考文献,并且许多基因座可以使用参考文献。然后,我有一个ManyToMany关系。
但是,在我的情况下,如果没有基因链接,参考文献就没有了,我不想把它保存在我的BDD中。
尝试列表:
Reference.php
/**
* Reference
*
* @ORM\Table(name="reference")
* @ORM\Entity(repositoryClass="AppBundle\Repository\ReferenceRepository")
*/
class Reference
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Locus", inversedBy="references")
*/
private $locus;
public function addLocus(Locus $locus)
{
if (!$this->locus->contains($locus)) {
$this->locus->add($locus);
$locus->addReference($this);
}
return $this;
}
public function removeLocus(Locus $locus)
{
if ($this->locus->contains($locus)) {
$this->locus->removeElement($locus);
}
return $this;
}
public function getLocus()
{
return $this->locus;
}
Locus.php
/**
* @ORM\Entity(repositoryClass="AppBundle\Repository\LocusRepository")
*/
class Locus extends GeneticEntry
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Reference", mappedBy="locus", orphanRemoval=true)
*/
private $references;
public function addReference(Reference $reference)
{
$this->references->add($reference);
return $this;
}
public function removeReference(Reference $reference)
{
if ($this->references->contains($reference)) {
$this->references->removeElement($reference);
}
return $this;
}
public function getReferences()
{
return $this->references;
}
答案 0 :(得分:0)
目前我选择在postUpdate事件上使用EventListener,我测试了ArrayCollection,如果为空,我删除了实体:
ReferenceListener.php:
<?php
namespace AppBundle\EventListener;
use AppBundle\Entity\Reference;
use Doctrine\ORM\Event\LifecycleEventArgs;
class ReferenceListener
{
public function postUpdate(LifecycleEventArgs $args)
{
$object = $args->getObject();
if (!$object instanceof Reference) {
return;
}
// If the Reference have no Locus and no Chromosomes, delete it
if ($object->getLocus()->isEmpty() && $object->getChromosomes()->isEmpty()) {
$args->getEntityManager()->remove($object);
$args->getEntityManager()->flush();
}
}
}