truncate all tables in laravel using eloquent

前端 未结 6 570
别跟我提以往
别跟我提以往 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:54

    Based on previous answers, I filter table names directly into the SQL query. I'm agree it's a small optimization but that avoids unnecessary loop.

    protected function truncateDatabase($excepts = []): void
    {
        $excepts = array_merge(['migrations'], $excepts);
        \DB::statement('SET foreign_key_checks=0');
        $table_names = \DB::query()->select('TABLE_NAME')->from('information_schema.tables')
            ->where('TABLE_SCHEMA', \DB::getDatabaseName())
            ->whereNotIn('TABLE_NAME', $excepts)
            ->get()
            ->pluck('TABLE_NAME')
            ->toArray();
        foreach ($table_names as $table_name) {
            \DB::table($table_name)->truncate();
        }
        \DB::statement('SET foreign_key_checks=1');
    }
    

提交回复
热议问题