Doctrine2:多对一删除更新时的关系

时间:2014-11-07 15:51:56

标签: symfony doctrine-orm one-to-many cascade many-to-one

我有一个可以拥有许多屏幕截图的软件。

这是软件类:

class Software
{
   public function __construct()
   {
       $this->screenshots = new ArrayCollection();
   }

   /**
    * @ORM\OneToMany(targetEntity="Screenshot", mappedBy="software", cascade={"persist"})
    * @ORM\OrderBy({"sequence" = "ASC", "id" = "ASC"})
    */
   private $screenshots;


   public function setScreenshots($screenshots)
   {
       $this->screenshots = $screenshots;
   }
}

这是截图类:

class Screenshot
{
   /**
    * @ORM\ManyToOne(targetEntity="Software", inversedBy="screenshots")
    * @ORM\JoinColumn(name="software_id", referencedColumnName="id")
    */
   private $software;

   /**
    * @param mixed $software
    */
   public function setSoftware($software)
   {
       $this->software = $software;
   }

当我生成一些新截图时,将它们放入数组集合并调用 带有新屏幕截图的$software->setScreenshots($newScreenshots)一切正常。新的屏幕截图已保存,并且可以参考该软件。

但是当我生成一些其他截图并再次调用该方法时,它不会删除旧屏幕截图。新截图刚刚添加。

有没有办法获得某种级联选项,以便删除旧的屏幕截图?或者至少删除对软件的引用?

2 个答案:

答案 0 :(得分:1)

您可以让de数据库完成工作(DBAL方):

user:
        targetEntity: User
        inversedBy: points
        joinColumn:
            name: user_id
            referencedColumnName: id
            onDelete: 'cascade' #this is important for u
        fetch: EAGER

答案 1 :(得分:0)

最简单的解决方案是手动删除它们:

foreach ( $software->getScreenshots() as $scrshot){
    $em->remove($scrshot);
}
$software->setScreenshots($newScreenshots);

但是,除了这个解决方案之外,您是否尝试在反向或关系上定义orphanRemoval?也许这会有所帮助,但我不确定:

/**
 * @ORM\OneToMany(targetEntity="Screenshot", mappedBy="software", cascade={"persist"}, orphanRemoval=true)
 * @ORM\OrderBy({"sequence" = "ASC", "id" = "ASC"})
 */
private $screenshots;