I am building an app where USERS can give a SCORE to some ANSWERS left by the community.
here the schema/relations of the entities:
ANSWER (one to many with) SCORE (many to one with) USER
I want that when i remove an ANSWER, the SCORES related to that ANSWER are also deleted...
BUT when I have more than one SCORE, then symfony triggers this exception:
"SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`symfony`.`Score`, CONSTRAINT `FK_6F8F552A4AB7A507` FOREIGN KEY (`answer_id`) REFERENCES `Answer` (`id`))
I must say that it works fine if there is only one SCORE related to that answer. (strange?)
Here my entities: you will see that I do have the cascade={"remove"}, I emphasis the fact that SCORE id is build on ANSWER_ID and USER_ID. (because I want that a SCORE can only be delivered once for an answer by a user).
class=Answer
{
/**
* @ORM\OneToMany(targetEntity="XX\BlogBundle\Entity\Score", mappedBy="answer", cascade={"persist", "remove"})
**/
private $scores;
/**
* @param \XX\BlogBundle\Entity\Score $scores
*/
public function removeScore(\XX\BlogBundle\Entity\Score $score)
{
$this->scores->removeElement($score);
}
// OTHER ATTRIBUTES ETC
}
.
class=Score
{
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="XX\BlogBundle\Entity\Anwer", inversedBy="scores")
*/
private $answer;
/**
* @ORM\Id
* @ORM\ManyToOne(targetEntity="XX\BlogBundle\Entity\User", cascade={"persist"})
*/
private $user;
/**
* @var smallint
* @ORM\Column(name="valeur", type="smallint", length=10, nullable=true)
*/
private $value;
// SETTER AND GETTER
}
.
class User
{
/**
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
* @ORM\Column(name="name", type="string", length=10)
*/
private $name;
}
I would remove them manually instead of any cascade operations.. Something like this:
I don't know how
cascade=removeworks with collections (I've never been interested in using cascade operations), but in your case doctrine is saying that it cant remove parent (Answer object) without deleting all its collection (related Score objects)..