truncate all tables in laravel using eloquent

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

    Here is my answer based on @Hao Luo. Moreover, it has these pros:

    1. You do not need to install any extra package (no need for doctrine)
    2. It supports Laravel 5 (or newer) very well
    3. It disables foreign key constraint (If you truncate without caring about the orders and enables foreign key constraint, you will likely get an error)

    Here is the code:

    DB::statement("SET foreign_key_checks=0");
    $databaseName = DB::getDatabaseName();
    $tables = DB::select("SELECT * FROM information_schema.tables WHERE table_schema = '$databaseName'");
    foreach ($tables as $table) {
        $name = $table->TABLE_NAME;
        //if you don't want to truncate migrations
        if ($name == 'migrations') {
            continue;
        }
        DB::table($name)->truncate();
    }
    DB::statement("SET foreign_key_checks=1");
    

    Hope you like it! :)

提交回复
热议问题