在laravel中显示DB类的mysql错误

问题描述 投票:0回答:1

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

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

认为$status = false意味着更新行动存在问题。如何显示DB类的mysql错误?

php laravel laravel-5.5
1个回答
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的源代码中查看此逻辑。

Class: \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
        );
    }
    ......
}
© www.soinside.com 2019 - 2024. All rights reserved.