当前位置:

Laravel实现软删除

本文最后更新于2022-08-12,已超过 1年没有更新,如果文章内容、图片或者下载资源失效,请留言反馈,我会及时处理,谢谢!

温馨提示:本文共2644个字,读完预计7分钟。

Laravel实现软删除

Laravel 的 Eloquent ORM 提供了一个漂亮、简洁的 ActiveRecord 实现来和数据库交互。每个数据库表都有一个对应的「模型」用来与该表交互。你可以通过模型查询数据表中的数据,以及在数据表中插入新记录。

官方文档对于软删除的解释如下:

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

 

下面我们来编写一个用户表,实现软删除的例子:

  • 创建生成模型和迁移文件
php artisan make:model User -m

实体类:

class User
{

    // 调用定义的trait类 和继承效果一样 
    // 开启软删除
    use SoftDeletes;
    // 设置添加的数据
    // 拒绝不添加的数据 使用create才有效
    protected $guarded = [];
    
    // 软删除标识字段
    protected $dates = ['deleted_at'];
}

实体类必须加上 use SoftDeletes;

  • 迁移文件:
class CreateUsersTable extends Migration
{

    /**
     * 用户表
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            // 角色
            $table->unsignedInteger('role_id')->default(0)->comment('角色ID');
            $table->string('username', 50)->comment("账号");
            $table->string('truename', 20)->default('未知')->comment("账号");
            $table->string('password', 255)->comment('密码');
            $table->string('email', 50)->nullable()->comment('邮箱');
            $table->string('phone', 15)->default('')->comment('手机号码');
            $table->enum('sex', ['先生','女士'])->default('先生')->comment('性别');
            $table->char('last_ip', 15)->default('')->comment('登录IP');
            $table->timestamps();
            // 实现软删除,需要添加delete_at字段,$table->softDeletes();
            $table->softDeletes();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

执行php artisan migrate创建表

表结构如下:

Laravel实现软删除-Mr.Li's Blog

  • 查询方法:

如果不使用withTrashed(),已经进行了软删除的数据就查不出来,因为Laravel默认查询结果会自动剔除已被软删除的结果。

   public function index(){
       // 分页  withTrashed 显示所有的,包括已经进行了软删除的
       $data = User::orderBy('id', 'desc')->withTrashed()->paginate($this->pageSize);
       return view('admin.user.index', compact('data'));
   }

当然,使用onlyTrashed() 方法可以获取已软删除的模型

    public function index(){
        $data = User::orderBy('id', 'desc')->onlyTrashed()->paginate($this->pageSize);
        return view('admin.user.index', compact('data'));
    }
  • 软删除方法:

直接调用delete()方法或者destroy()方法即可

    public function del(int $id){
        User::destroy($id);
        // 删除
		// User::find($id)->delete();
        return ['status' => '0', 'msg' => '删除成功'];
    }

调用删除方法删除数据之后,因为我们开启了软删除,所以在调用删除方法之前,deleted_at字段是为空的,调用之后会给deleted_at赋值上当前的时间戳,标识该记录已经被 “删除”。

Laravel实现软删除-Mr.Li's Blog

  • 永久删除

直接删除数据

    public function del(int $id){
        User::forceDeleted($id);
        return ['status' => '0', 'msg' => '删除成功'];
    }
  • 恢复删除

既然是软删除,那就可以进行数据的恢复,简单地说就是把deleted_at字段置空就行。Laravel也为我们提供了restore()方法

    public function restore(int $id){
        User::onlyTrashed()->where('id', $id)->restore();
        return redirect(route('admin.user.index'))->with(['success' => '还原成功']);
    }
本文链接:,转发请注明来源!
评论已关闭。