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

前端 未结 14 2101
鱼传尺愫
鱼传尺愫 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: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()
    

提交回复
热议问题