当前位置:网站首页>Laravel implements soft deletion

Laravel implements soft deletion

2022-06-22 03:53:00 Healthy brick carrier

Laravel Realize soft deletion

Laravel Of Eloquent ORM Provides a beautiful 、 concise ActiveRecord To interact with the database . Each database table has a corresponding 「 Model 」 Used to interact with this table . You can query the data in the data table through the model , And inserting new records in the data table .

Official documents The explanation of soft deletion is as follows :

In addition to actually deleting database records ,Eloquent It's fine too 「 Soft delete 」 Model . Soft deleted models are not really deleted from the database . in fact , Is set on the model deleted_at Property and write its value to the database . If deleted_at Value is not empty , Represents that this model has been soft deleted . If you want to enable the soft delete function of the model , You need to use... On the model Illuminate\Database\Eloquent\SoftDeletes


Let's write a user table , An example of implementing soft deletion :

  • Create build models and migration files
php artisan make:model User -m

Entity class :

class User
{
    

    //  Call defined trait class   Same as inheritance  
    //  Enable soft delete 
    use SoftDeletes;
    //  Set the added data 
    //  Reject data not added   Use create It works 
    protected $guarded = [];
    
    //  Soft delete identification field 
    protected $dates = ['deleted_at'];
}

Entity class must be added with use SoftDeletes;

  • The migration file :
class CreateUsersTable extends Migration
{
    

    /** *  User table  */
    public function up()
    {
    
        Schema::create('users', function (Blueprint $table) {
    
            $table->bigIncrements('id');
            //  role 
            $table->unsignedInteger('role_id')->default(0)->comment(' role ID');
            $table->string('username', 50)->comment(" account number ");
            $table->string('truename', 20)->default(' Unknown ')->comment(" account number ");
            $table->string('password', 255)->comment(' password ');
            $table->string('email', 50)->nullable()->comment(' mailbox ');
            $table->string('phone', 15)->default('')->comment(' Phone number ');
            $table->enum('sex', [' sir ',' ma'am '])->default(' sir ')->comment(' Gender ');
            $table->char('last_ip', 15)->default('')->comment(' Sign in IP');
            $table->timestamps();
            //  Realize soft deletion , Need to add delete_at Field ,$table->softDeletes();
            $table->softDeletes();
        });
    }

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

perform php artisan migrate Create table

The table structure is as follows :

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-R4vrLGRp-1594996196435)(1.png)]

  • Query methods :

If not used withTrashed(), Data that has been soft deleted cannot be found , because Laravel The default query results will automatically reject the results that have been soft deleted .

   public function index(){
    
       //  Pagination  withTrashed  Show all , Including those that have been soft deleted 
       $data = User::orderBy('id', 'desc')->withTrashed()->paginate($this->pageSize);
       return view('admin.user.index', compact('data'));
   }

Of course , Use onlyTrashed() Methods can be only Get the soft deleted model

    public function index(){
    
        $data = User::orderBy('id', 'desc')->onlyTrashed()->paginate($this->pageSize);
        return view('admin.user.index', compact('data'));
    }
  • Soft deletion method :

Call directly delete() Methods or destroy() The method can

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

After calling the delete method to delete the data , Because we have enabled soft deletion , So before calling the delete method ,deleted_at Field is empty , After calling, the deleted_at The current timestamp on the assignment , Identify that the record has been “ Delete ”.

[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-o8EqmV8s-1594996196445)(2.jpg)]

  • Permanently delete

Delete data directly

    public function del(int $id){
    
        User::forceDeleted($id);
        return ['status' => '0', 'msg' => ' Delete successful '];
    }
  • Resume delete

Since it is a soft delete , Then you can recover the data , Simply put, it means to put deleted_at Just leave the field blank .Laravel It also provides us with restore() Method

    public function restore(int $id){
    
        User::onlyTrashed()->where('id', $id)->restore();
        return redirect(route('admin.user.index'))->with(['success' => ' Restore successful ']);
    }
原网站

版权声明
本文为[Healthy brick carrier]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211630247601.html