mercredi 24 mai 2017

Doctrine Cascade Delete OneToMany self Referencing

Hello i have an issue with my symfony project

I have a listener entity

/**
 * 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
{
    ...
}

in this class there is a sponsoredListeners property

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

this property is an ArrayCollection of Listener entities (the current class)

listeners are added in this array collection using this method

/**
  * 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;
    }

There problem is that when i try to delete all listeners from my listener tables during my testing i get these errors

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

if i understand what is happening he is trying to delete listeners with are "linked" with other listeners for sponsoredListeners.

I think i need a cascade delete but not sure how to do it. If someone can explain me it could be really cool

here is the listener table

Column Type Comment id int(11) Auto Increment
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)
sponsored_at datetime NULL
created_at datetime
updated_at datetime NULL

Aucun commentaire:

Enregistrer un commentaire