Laravel 4中如何获取执行失败的INSERT查询SQL语句
解决Laravel 4中无法捕获失败INSERT语句SQL的问题
问题根源分析
你的代码存在几个关键问题导致无法捕获失败的INSERT语句:
enableQueryLog()调用位置错误,放在了事务闭包之后,导致查询日志在执行INSERT前并未启用- 嵌套跨连接事务可能干扰日志记录逻辑
- 未确认
Customer模型是否使用了目标数据库连接connection_01
修复方案
1. 修正代码结构,提前启用查询日志
调整代码,确保在执行任何查询前启用目标连接的查询日志,并简化事务逻辑:
class MigrationData { protected $log = ""; public function executeMigration($id, $own, $company_id = null) { // 初始化目标连接并启用查询日志 $dbConn = DB::connection('connection_01'); $dbConn->enableQueryLog(); try { $dbConn->transaction(function() use($id, $own, $company_id) { // 业务逻辑 $customer = new Customer(); // 给模型赋值属性(示例) // $customer->name = 'xxx'; // $customer->email = 'xxx@xxx.com'; $customer->save(); Log::debug('成功执行的查询:', $dbConn->getQueryLog()); }); } catch (\Exception $e) { // 捕获事务内的所有异常,记录查询日志 Log::debug('异常前的查询日志:', $dbConn->getQueryLog()); // 记录Oracle异常的详细信息,部分PDO驱动会包含执行的SQL Log::debug('异常详情:', [ 'message' => $e->getMessage(), 'sql' => property_exists($e, 'queryString') ? $e->queryString : '无法直接提取SQL', 'trace' => $e->getTraceAsString() ]); throw $e; // 重新抛出异常确保事务回滚 } } }
2. 确认模型使用正确连接
确保Customer模型指定了目标数据库连接,否则save()会使用默认连接,导致日志无法捕获:
class Customer extends Eloquent { protected $connection = 'connection_01'; }
3. 手动构建SQL作为 fallback
如果查询日志仍无法捕获失败的INSERT,可以通过模型属性手动拼接SQL:
// 在catch块中添加以下代码 $customer = new Customer(); // (确保这里已完成属性赋值) $table = $customer->getTable(); $columns = implode(', ', array_keys($customer->getAttributes())); $values = implode(', ', array_map(function($val) use($dbConn) { return $dbConn->getPdo()->quote($val); }, $customer->getAttributes())); $manualSql = "INSERT INTO {$table} ({$columns}) VALUES ({$values})"; Log::debug('手动构建的INSERT语句:', $manualSql);
内容的提问来源于stack exchange,提问作者sineverba
相关产品推荐
相关产品推荐

