Symfony 2.7,Doctrine级联删除

时间:2016-09-30 07:19:43

标签: symfony doctrine-orm

我尝试使用学说cascade={"remove"},但它不起作用。

情况: 我宣布包含许多图片(一张图片只能参考一张图片)。我希望当我删除数据库中的通知时,它也会删除图片。

这是我的代码:

实体宣布:

/**
 * Announce
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Announce\AnnounceRepository")
 */
class Announce
{
    /**
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Announce\PictureAnnounce", inversedBy="coverAnnounce")
     * @ORM\JoinColumn(name="cover_picture_id", referencedColumnName="id", nullable=true)
     */
    private $coverPicture; 

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Announce\PictureAnnounce", mappedBy="announce", cascade={"remove"})
     */
    private $pictureAnnounces; 
}

实体图片宣布:

/**
 * AppBundle\Entity\Announce\PictureAnnounce
 *
 * @ORM\Table(name="picture_announce")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Announce\PictureAnnounceRepository")
 * @ORM\HasLifecycleCallbacks
 */
class PictureAnnounce
{
    /**
     * @ORM\OneToOne(targetEntity="AppBundle\Entity\Announce\Announce", mappedBy="coverPicture", cascade={"persist"})
     */
    private $coverAnnounce;

    /**
     * @var Announce $announce
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Announce\Announce", inversedBy="pictureAnnounces")
     * @ORM\JoinColumn(name="announce_id", referencedColumnName="id", nullable=false)
    */
    private $announce;

删除代码(我将coverPicture设置为null,以便删除时不会出现外键错误)

$announce->setCoverPicture(null);
$em->flush();
$em->remove($announce);
$em->flush();

但我在外键上有错误

  

SQLSTATE [23000]:完整性约束违规:1451无法删除或   更新父行:外键约束失败

PS:我无法找到如何正确呈现我的代码:s

PS:这种解决方法有效,但不是级联工作的方式吗?

if(count($announce->getPictureAnnounces()) > 0) { 
   $pictureAnnounces = $announce->getPictureAnnounces();
   foreach ($pictureAnnounces as $pictureAnnounce) { 
     $em->remove($pictureAnnounce);
   }
   $em->flush(); 
} // Then remove the announce

0 个答案:

没有答案