阅读(3709) (6)

Laravel 8 软删除

2021-07-07 10:18:54 更新

除了真实删除数据库记录,Eloquent 也可以「软删除」模型。软删除的模型并不是真的从数据库中删除了。 事实上,是在模型上设置了 deleted_at 属性并将其值写入数据库。如果 deleted_at 值非空,代表这个模型已被软删除。如果要开启模型软删除功能,你需要在模型上使用 IlluminateDatabaseEloquentSoftDeletes trait:

<?php

namespace AppModels;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;

class Flight extends Model
{
    use SoftDeletes;
} 

技巧:SoftDeletes 会自动将 deleted_at 属性转换成 DateTime / Carbon 实例。

当然,你需要把 deleted_at 字段添加到数据表中。Laravel数据迁移 有创建这个字段的方法:

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

public function down()
{
    Schema::table('flights', function (Blueprint $table) {
        $table->dropSoftDeletes();
    });
} 

那现在,当你在模型实例上使用 delete 方法,当前日期时间会写入 deleted_at 字段。同时,查询出来的结果也会自动排除已被软删除的记录。

你可以使用 trashed 方法来验证给定的模型实例是否已被软删除:

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