此示例代码适用于数据库:
$status = DB::table('post')->where('id', 2)->update([
'title' => 'new title',
'content' => 'new content'
]);
认为$status = false
表示更新操作时出现问题。如何显示DB类的mysql错误?
答案 0 :(得分:2)
使用Laravel的QueryException:
使用Illuminate \ Database \ QueryException;
try {
$status = DB::table('post')->where('id', 2)->update([
'title' => 'new title',
'content' => 'new content'
]);
} catch (QueryException $e) {
//var_dump($e->getMessage())
\Log::error('QueryException: ' . $e->getMessage())
}
<强> 更新: 强> 当SQL执行出错时,为什么laravel抛出QueryException。请参阅laravel的源代码中的逻辑。
/**
* Run a SQL statement and log its execution context.
*
* @param string $query
* @param array $bindings
* @param \Closure $callback
* @return mixed
*
* @throws \Illuminate\Database\QueryException
*/
protected function run($query, $bindings, Closure $callback)
{
$this->reconnectIfMissingConnection();
$start = microtime(true);
try {
$result = $this->runQueryCallback($query, $bindings, $callback);
} catch (QueryException $e) {
$result = $this->handleQueryException(
$e, $query, $bindings, $callback
);
}
......
}