truncate all tables in laravel using eloquent

前端 未结 6 652
别跟我提以往
别跟我提以往 2021-02-05 02:52

Is there a way I could truncate all the tables in a db using eloquent or fluent in laravel 4? I do not want to specify table names, I just want to truncate all the tables. In ot

6条回答
  •  花落未央
    2021-02-05 03:43

    This is how i truncate all tables inside a database (including table exceptions), it works for me.

        // set tables don't want to trucate here
        $excepts = ['migrations'];
        $tables = DB::connection()
        ->getPdo()
        ->query("SHOW FULL TABLES")
        ->fetchAll();
        $tableNames = [];
    
        $keys = array_keys($tables[0]);
        $keyName = $keys[0];
        $keyType = $keys[1];
    
        foreach ($tableNames as $name) {
            //if you don't want to truncate migrations
            if (in_array($name[$keyName], $excepts))
                continue;
    
            // truncate tables only
            if('BASE TABLE' !== $name[$keyType])
                continue;
    
            \DB::table($name)->truncate();
        }
    

提交回复
热议问题