我有很多相关的用户和组,然后删除在我得到的用户中使用的组:
DBALException:执行“DELETE FROM Groups WHERE id = ?”时发生异常 带参数...完整性约束违规:1451 无法删除或更新父行:外键约束失败...
DBALException:执行“DELETE FROM Groups WHERE id = ?”时发生异常 带参数...完整性约束违规:1451 无法删除或更新父行:外键约束失败
...这是正常的,我如何捕捉异常,或者检查它是否以某种方式使用?
除了ON DELETE在数据库级别使用子句(这显然是优雅且独立于框架的方式)之外,您可能希望直接在代码中检查组的现有用户。在这种情况下,您可以执行另一个查询。
$em = $this->getDoctrine()->getEntityManager();
// Set your group id as the desired criterion
$criteria = array('GroupId' => $group->getId);
// Get all users that match the criterion
$users = $em->getRepository("YourBundle:User")->findBy($criteria);
// Check whether the returned array is empty
if(count($users) != 0){
// Do your exception handling
}else {
// Do regular operations, like deleting the group
}
如果要在删除组时删除组内的所有用户,可以告诉学说级联删除。所以元数据文件的 oneToMany 部分(比如 groups.orm.yml)看起来像
oneToMany:
users:
targetEntity: Users
mappedBy: user
cascade: [remove]
这意味着您可能已经使用外键设置了数据库,如下所示:
|---------|
| User |
|---------|
| id |
| groupId |
|---------|
|-------|
| Group |
|-------|
| id |
|-------|
哪里User.groupId指Group.id。这意味着当您删除一个组时,您需要定义数据库应该对属于该组的用户做什么。
根据您的意图,可以更改您的外键约束来处理这种情况。你没有提到你正在使用什么数据库类型,但我知道在 MySQL 中你可以有一个CONSTRAINTwithON DELETE子句,并给它RESTRICT(默认,你现在看到的)选项,CASCADE(删除所有关联的用户与该组),并且SET NULL(为删除组的用户设置为)groupId。NULL