How to delete all the rows in a table using Eloquent?

前端 未结 14 2072
鱼传尺愫
鱼传尺愫 2021-01-30 09:35

My guess was to use the following syntax:

MyModel::all()->delete();

But that did not work. I\'m sure it\'s super simple, but I\'ve searched

相关标签:
14条回答
  • 2021-01-30 10:36

    I've seen both methods been used in seed files.

    // Uncomment the below to wipe the table clean before populating
    
    DB::table('table_name')->truncate();
    
    //or
    
    DB::table('table_name')->delete();
    

    Even though you can not use the first one if you want to set foreign keys.

    Cannot truncate a table referenced in a foreign key constraint

    So it might be a good idea to use the second one.

    0 讨论(0)
  • 2021-01-30 10:36

    In a similar vein to Travis vignon's answer, I required data from the eloquent model, and if conditions were correct, I needed to either delete or update the model. I wound up getting the minimum and maximum I'd field returned by my query (in case another field was added to the table that would meet my selection criteria) along with the original selection criteria to update the fields via one raw SQL query (as opposed to one eloquent query per object in the collection).

    I know the use of raw SQL violates laravels beautiful code philosophy, but itd be hard to stomach possibly hundreds of queries in place of one.

    0 讨论(0)
  • 2021-01-30 10:36

    In my case laravel 4.2 delete all rows ,but not truncate table

    DB::table('your_table')->delete();

    0 讨论(0)
  • 2021-01-30 10:38

    Laravel 5.2+ solution.

    Model::getQuery()->delete();
    

    Just grab underlying builder with table name and do whatever. Couldn't be any tidier than that.

    Laravel 5.6 solution

    \App\Model::query()->delete();
    
    0 讨论(0)
  • 2021-01-30 10:38

    You can use Model::truncate() if you disable foreign_key_checks (I assume you use MySQL).

    DB::statement("SET foreign_key_checks=0");
    Model::truncate();
    DB::statement("SET foreign_key_checks=1");
    
    0 讨论(0)
  • 2021-01-30 10:38

    Can do a foreachloop too..

    $collection = Model::get();
    
    foreach($collection as $c) {
    
    $c->delete();
    
    }
    
    0 讨论(0)
提交回复
热议问题