Doctrine Cascade删除OneToMany自我引用

时间:2017-05-24 14:11:44

标签: php symfony testing doctrine-orm doctrine

您好我的symfony项目存在问题

我有一个监听器实体

/**
 * Listener
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\ListenerRepository")
 * @ORM\Table("listeners", uniqueConstraints={@ORM\UniqueConstraint(name="sponsor_code", columns={"sponsor_code"})})
 * @ORM\HasLifecycleCallbacks()
 */
class Listener implements ListenerInterface
{
    ...
}

在这个课程中有一个sponsListeners属性

/**
  * @Groups({"listener_sponsored"})
  *
  * @ORM\OneToMany(targetEntity="Listener", mappedBy="sponsor")
  */
    private $sponsoredListeners;

此属性是监听器实体的ArrayCollection(当前类)

使用此方法在此数组集合中添加

侦听器

/**
  * Add sponsored Listener
  *
  * @param \AppBundle\Entity\Listener $sponsoredListener
  *
  * @return Listener
  */
  public function addSponsoredListener(\AppBundle\Entity\Listener $sponsoredListener)
    {
        if (!$this->sponsoredListeners->contains($sponsoredListener)) {
            $this->sponsoredListeners[] = $sponsoredListener;
        }

        $sponsoredListener->setSponsor($this); // just set the sponsor property for the listener given in parameters of this function (addSponsoredListener)    
        return $this;
    }

问题在于,当我在测试期间尝试从我的监听器表中删除所有监听器时,我得到了这些错误

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`myradio_test`.`listeners`, CONSTRAINT `FK_CEFB12DB12F7FB51` FOREIGN KEY (`sponsor_id`) REFERENCES `listeners` (`id`))

/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php:60
/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:128
/var/www/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:996
/var/www/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Purger/ORMPurger.php:149
/var/www/vendor/doctrine/data-fixtures/lib/Doctrine/Common/DataFixtures/Executor/AbstractExecutor.php:136
/var/www/vendor/liip/functional-test-bundle/Test/WebTestCase.php:451
/var/www/src/ApiBundle/Tests/Controller/ArtistsControllerTest.php:16
/var/www/src/ApiBundle/Tests/Controller/ArtistsControllerTest.php:27

如果我理解发生了什么,他试图用#"链接"删除听众。与sponsListeners的其他听众一起使用。

我想我需要级联删除,但不知道该怎么做。如果有人能解释我的话可能真的很酷

这是监听器表

列类型注释 id int(11)自动增量
account_id int(11)NULL
sponsor_id int(11)NULL
station_id int(11)NULL
firstname varchar(100)NULL
gender varchar(255)NULL
birthyear int(11)NULL
picture varchar(255)NULL
sponsor_code varchar(6)
spons_at datetime NULL
created_at datetime
updated_at datetime NULL

1 个答案:

答案 0 :(得分:1)

对于类属性,您需要删除set注释onDelete =“SET NULL”并使其可以为空