Laravel检查约束是否违反 [英] Laravel check for constraint violation
问题描述
我很好奇,是否有一种方法可以在删除记录或将记录插入数据库时检查是否存在约束冲突错误.
I was curious if there is a way we can check if there is a constraint violation error when delete or insert a record into the database.
抛出的异常称为"QueryException",但这可能是多种错误.如果我们可以检查异常的具体错误,那就太好了.
The exception thrown is called 'QueryException' but this can be a wide range of errors. Would be nice if we can check in the exception what the specific error is.
推荐答案
您正在寻找23000 Error code (Integrity Constraint Violation)
.如果您查看 QueryException
类,则它从 PDOException
,因此您可以访问$errorInfo
变量.
You are looking for the 23000 Error code (Integrity Constraint Violation)
. If you take a look at QueryException
class, it extends from PDOException
, so you can access to $errorInfo
variable.
要捕获此错误,您可以尝试:
To catch this error, you may try:
try {
// ...
} catch (\Illuminate\Database\QueryException $e) {
var_dump($e->errorInfo);
}
// Example output from MySQL
array (size=3)
0 => string '23000' (length=5)
1 => int 1452
2 => string 'Cannot add or update a child row: a foreign key constraint fails (...)'
更具体地说(重复的条目,不为null,添加/更新子行,删除父行...),这取决于每个DBMS:
To be more specific (Duplicate entry, not null, add/update child row, delete parent row...), it depends on each DBMS:
- PostgreSQL 和
$e->getCode()
直接 - MySQL , MariaDB 和
- PostgreSQL and SQL server follow the SQL standard's conventions for
SQLSTATE
code, so you may return the first value from the array$e->errorInfo[0]
or call$e->getCode()
directly - MySQL, MariaDB and SQLite do not strictly obey the rules, so you need to return the second value from the array
$e->errorInfo[1]
对于laravel,处理错误很容易,只需将此代码添加到"app/start/global.php"文件中(或创建
For laravel, handling errors is easy, just add this code in your "app/start/global.php" file ( or create a service provider):
App::error(function(\Illuminate\Database\QueryException $exception)
{
$error = $exception->errorInfo;
// add your business logic
});
这篇关于Laravel检查约束是否违反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!