原则 2 OneToMany 级联 SET NULL
错误
无法删除或更新父行:外键约束失败。
课程
class Teacher {
/**
*@ORM\OneToMany(targetEntity="publication", mappedBy="teacher")
*/
protected $publications;
}
class Publication {
/**
* @ORM\ManyToOne(targetEntity="Teacher", inversedBy="publications")
* @ORM\JoinColumn(name="teacher_id", referencedColumnName="id")
*/
protected $teacher;
}
我想要的
我想要的是当你删除教师时,id_teacher 被修改为 NULL。我想保留该出版物,但不提及教授。
我不知道在教义中如何做到这一点,可能吗?或者总是与老师有关系?
The error
Cannot delete or update a parent row: a foreign key constraint fails.
The classes
class Teacher {
/**
*@ORM\OneToMany(targetEntity="publication", mappedBy="teacher")
*/
protected $publications;
}
class Publication {
/**
* @ORM\ManyToOne(targetEntity="Teacher", inversedBy="publications")
* @ORM\JoinColumn(name="teacher_id", referencedColumnName="id")
*/
protected $teacher;
}
I want
What I want is to make it that when you delete a teacher, the id_teacher is modified to NULL. I want to keep the publication but without reference to Professor.
I don't know how do that in Doctrine, Is it possible? Or always the relationship has to be with a teacher?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该在实体 Publication 的注释中添加选项
onDelete="SET NULL"
,如下所示:此修改在表声明本身中注册。因此,您需要进行数据库迁移或架构更改才能使其生效。
You should add the option
onDelete="SET NULL"
in the annotation of your entity Publication like this:This modification is registered in the table declaration itself. Hence, you need a database migration or a schema change for this to take effect.
对于 Symfony 6 (PHP 8)(引擎“InnoDB”)
For Symfony 6 (PHP 8) (Engine 'InnoDB')
老问题,所以这适合任何寻找解决方案的人。
如果您不想对数据库架构进行任何更改,您可以使用学说事件系统:
Old question, so this is for anyone searching for solution.
In case you don't want to make any changes to database schema you can make use of doctrine event system: