【发布时间】:2019-12-31 04:48:24
【问题描述】:
laravel Model->save() 不会抛出数据库异常,我想检查列的唯一约束(没有主键或其他外键)。
当Model->save()返回false时,有什么方法可以得到消息的数据库错误代码?
【问题讨论】:
标签: php mysql laravel error-handling eloquent
laravel Model->save() 不会抛出数据库异常,我想检查列的唯一约束(没有主键或其他外键)。
当Model->save()返回false时,有什么方法可以得到消息的数据库错误代码?
【问题讨论】:
标签: php mysql laravel error-handling eloquent
你可以试试QueryException。捕获任何SQL 语法或查询错误。
use Illuminate\Database\QueryException
try {
$model = Model::find($id);
$model->name = 'joe';
$model->save();
} catch (QueryException $e) {
dd($e->getMessage());
}
【讨论】:
try 中放入你的代码来更新或创建你的模型,
Model::find($id)->update(['name' => 'test']); :)
您可以在数据库中使用“UNIQUE”列,然后通过 QueryException 处理错误。
【讨论】:
=> If you have label exists, See below error:
"Exception message:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'TEST GO' for key 'materials_label_unique' (SQL: insert into `materials` (`label`, `updated_at`, `created_at`) values (TEST GO, 2019-08-27 09:53:47, 2019-08-27 09:53:47)) with code: 23000"
function insertMaterial()
{
try {
$material = new Materials;
$material->label = "TEST GO";
if( $material->save() ) {
return "True as a string";
} else {
return "False as a string";
}
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
=> If you'll try to find the non-existing record, See below error:
"Exception message: Creating default object from the empty value with code: 0"
function insertMaterial()
{
try {
$material = Materials::find(1111);
$material->label = "TEST GO";
if( $material->save() ) {
return "True as a String";
} else {
return "False as a String";
}
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
【讨论】: