从数据库中删除项目失败并返回“无法删除或更新父行:外键约束失败”Yii。
deleteAction:
public function run($id)
{
$model = $this->findModel($id);
if ($this->checkAccess) {
call_user_func($this->checkAccess, $this->id, $model);
}
if ($model->delete() === false) {
throw new ServerErrorHttpException('Failed to delete the object for unknown reason.');
}
Yii::$app->getResponse()->setStatusCode(204);
}
如何解决此问题?
答案 0 :(得分:2)
这意味着此记录存在约束。 例如,你有
表:用户 id为主键
带有约束
表:个人资料 user_id - > user.id
这可以防止它被删除。
您必须首先删除相关记录,如:
public function actionDelete($id)
{
// delete profile first to handle foreign key constraint
$user = $this->findModel($id);
$profile = $user->profile;
$profile->delete();
$user->delete();
return $this->redirect(['index']);
}