在laravel中显示DB类的mysql错误

时间:2018-03-06 05:55:10

标签: php laravel laravel-5.5

此示例代码适用于数据库:

    $status = DB::table('post')->where('id', 2)->update([
        'title' => 'new title',
        'content' => 'new content'
    ]);

认为$status = false表示更新操作时出现问题。如何显示DB类的mysql错误?

1 个答案:

答案 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的源代码中的逻辑。

类:\ Illuminate \ Database \ Connection

/**
 * 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
        );
    }
    ......
}