Soft Delete all records from a table in laravel 5

2019-01-29 14:05发布

问题:

Is there any way to soft delete all the existing rows in a table? I have tried ( Prospect::delete(); ) it deleted all the rows permanently, But it doesn't work in soft deleting.

回答1:

If you are using Laravel framework older than 4.2, then you can set the soft delete in your model as,

class ModelName extends Eloquent {
    protected $table = 'table_name';
    protected $softDelete = true;
}

If you are using Laravel framework 4.2, then you can set the soft delete in your model as,

use Illuminate\Database\Eloquent\SoftDeletingTrait;
class ModelName extends Eloquent {
    use SoftDeletingTrait;
    protected $table = 'table_name';
}

If you are using Laravel framework above 4.2, then you can set the soft delete in your model as,

use Illuminate\Database\Eloquent\SoftDeletes;
class ModelName extends Eloquent {
    use SoftDeletes;
    protected $table = 'table_name';
}

I hope you are using Laravel 5. So you can use the third method.



回答2:

look at this soft delete

use this trait in your model :

use Illuminate\Database\Eloquent\SoftDeletes;

and add this to your model and database schema :

model:

class Flight extends Model
{
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['deleted_at'];
}

database schema

Schema::table('flights', function ($table) {
    $table->softDeletes();
});

Now, when you call the delete method on the model, the deleted_at column will be set to the current date and time. And, when querying a model that uses soft deletes, the soft deleted models will automatically be excluded from all query results.

To determine if a given model instance has been soft deleted, use the trashed method:

if ($flight->trashed()) {
    //
}


回答3:

It usually not delete rows in database.You should add a column isActive etc. and set it (1/0) or (true/false). if you want show rows,you should "Select * from table Where isActive=1"