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

前端 未结 14 2070
鱼传尺愫
鱼传尺愫 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:15

    I wanted to add another option for those getting to this thread via Google. I needed to accomplish this, but wanted to retain my auto-increment value which truncate() resets. I also didn't want to use DB:: anything because I wanted to operate directly off of the model object. So, I went with this:

    Model::whereNotNull('id')->delete();
    

    Obviously the column will have to actually exists, but in a standard, out-of-the-box Eloquent model, the id column exists and is never null. I don't know if this is the best choice, but it works for my purposes.

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

    You can try this one-liner which preserves soft-deletes also:

    Model::whereRaw('1=1')->delete();
    
    0 讨论(0)
  • 2021-01-30 10:25

    The reason MyModel::all()->delete() doesn't work is because all() actually fires off the query and returns a collection of Eloquent objects.

    You can make use of the truncate method, this works for Laravel 4 and 5:

    MyModel::truncate();
    

    That drops all rows from the table without logging individual row deletions.

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

    I wasn't able to use Model::truncate() as it would error:

    SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table referenced in a foreign key constraint

    And unfortunately Model::delete() doesn't work (at least in Laravel 5.0):

    Non-static method Illuminate\Database\Eloquent\Model::delete() should not be called statically, assuming $this from incompatible context

    But this does work:

    (new Model)->newQuery()->delete()
    

    That will soft-delete all rows, if you have soft-delete set up. To fully delete all rows including soft-deleted ones you can change to this:

    (new Model)->newQueryWithoutScopes()->forceDelete()
    
    0 讨论(0)
  • 2021-01-30 10:31

    simple solution:

     Mymodel::query()->delete();
    
    0 讨论(0)
  • 2021-01-30 10:33

    There is an indirect way:

    myModel:where('anyColumnName', 'like', '%%')->delete();
    

    Example:

    User:where('id', 'like' '%%')->delete();
    

    Laravel query builder information: https://laravel.com/docs/5.4/queries

    0 讨论(0)
提交回复
热议问题