删除相关实体Symfony2
问题描述:
我有相关的实体。多对多关系和注释存在于只有一个实体:删除相关实体Symfony2
/**
* @ORM\ManyToMany(targetEntity="Event")
* @ORM\JoinTable(name="viewed_events",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="event_id", referencedColumnName="id")}
* )
**/
protected $viewedEvents;
问题是,当我试图删除事件实体,我得到Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
错误。我该如何解决这个问题?我尝试加入orphanRemoval=true
,如下所示:@ORM\ManyToMany(targetEntity="Event", orphanRemoval=true)
并尝试加入cascade="delete"
和cascade="all"
,但没有成功。
答
onDelete="CASCADE"
你们都要JoinColumn。
答
我给你一个简单的例子,这样你就可以计算出你需要在你的应用程序中添加/修改什么。
假设学生和课程实体之间存在M-N关系。
学生
class Student
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="StudentCourse", mappedBy="studentInverse", cascade={"persist", "remove"})
*/
protected $studentInverse;
public function __construct()
{
$this->studentInverse = new \Doctrine\Common\Collections\ArrayCollection();
}
}
课程
class Course
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="StudentCourse", mappedBy="courseMap", cascade={"persist", "remove"})
*/
protected $courseInverse;
public function __construct()
{
$this->courseInverse = new \Doctrine\Common\Collections\ArrayCollection();
}
}
STUDENTCOURSE(这个你在更感兴趣的)
class StudentCourse
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Course", inversedBy="courseInverse")
* @ORM\JoinColumn(name="course", referencedColumnName="id", nullable=false, onDelete="CASCADE")
*/
protected $courseMap;
/**
* @ORM\ManyToOne(targetEntity="Student", inversedBy="studentInverse")
* @ORM\JoinColumn(name="student", referencedColumnName="id", nullable=false, onDelete="CASCADE")
*/
protected $studentMap;
}