Laravel AppServiceProvider 公共函数启动 DB::listen 绑定=0

问题描述 投票:0回答:0
public function boot()
{
    DB::listen(function ($query) {
        $sql = $query->sql;
        $bindings = $query->bindings;
        
        if(stripos(substr($sql, 0, 10),'update') !== false){ 

           dd($query->bindings);

       }elseif(stripos(substr($sql, 0, 10),'insert') !== false){

        $do_sql = vsprintf(str_replace(['%', '?'], ['%%', "'%s'"], $sql), $bindings);

        
        $insertedId = DB::getPdo()->lastInsertId();
        preg_match('/insert into `(.*?)`/i', $do_sql, $matches);
        $tableName = $matches[1];

        // **********it will make update.bindings = 0***************
        $tableStructure = DB::select("SHOW COLUMNS FROM $tableName");


        $isFirstColumnAutoIncrement = false;
        if (!empty($tableStructure[0]->Extra) && $tableStructure[0]->Extra === 'auto_increment') {


            $isFirstColumnAutoIncrement = true;
            $ai_tableColumns = $tableStructure[0]->Field;


        }


    }


});
}

laravel:5.7 php:7.4 mysql:8

$tableStructure = DB::select("显示 $tableName 中的列"); 将使 update.bindings = 0.

if take off $tableStructure = DB::select("SHOW COLUMNS FROM $tableName"); 然后 update.bindings 将正确。

我想获取lastInsertId并添加到插入查询。

谢谢。

laravel database binding last-insert-id
© www.soinside.com 2019 - 2024. All rights reserved.