由于外键约束在Laravel中报告错误

huangapple go评论80阅读模式
英文:

Reporting Error Due to Foreign Key Constraint in Laravel

问题

在删除表中的某些行时,我在检查中收到以下错误消息

message: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

我知道这个错误是由于外键约束失败引起的。
我想显示一个错误消息,说明要删除的项目已被使用。

我正在使用Laravel 5.8,PHP 7.3,Mysql

有人对此有任何想法吗?

英文:

While deleting some rows from a table I am getting the following error in the inspect

> message: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

I know the error is arising due to the failing foreign key.
I would like to show an error message saying the deleting item is already used.

I am using Laravel 5.8, PHP 7.3, Mysql

Do anybody have any idea on this?

答案1

得分: 5

你可以将删除行的代码放在try块中,并在catch块中处理异常,就像这样。

try {
    // ...

} catch (\Illuminate\Database\QueryException $e) {
    var_dump($e->errorInfo);
}

var_dump()会提供有关异常的详细信息,然后您可以在不使脚本失败的情况下管理它。

英文:

You can put code that is deleting rows in try block and handle exceptions in catch block like this.

try {
  // ...

} catch (\Illuminate\Database\QueryException $e) {
    var_dump($e->errorInfo);
}

var_dump() will give details about the exceptions, then you can manage it without failing the script.

huangapple
  • 本文由 发表于 2020年1月3日 18:57:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577333.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定