当前位置:网站首页>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)]](/img/a0/decfca6d5a81fe15c57c08fdcff8f5.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)]](/img/1b/90064a769233b7b90219971928e533.png)
- 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 ']);
}
边栏推荐
- Comment dart asynchrone est implémenté
- 【BP回归预测】基于matlab GA优化BP回归预测(含优化前的对比)【含Matlab源码 1901期】
- Use of shutter stream
- How far is the memory computing integrated chip from popularization? Listen to what practitioners say | collision school x post friction intelligence
- 3DE new simulation status
- Larave 数据库备份 定时任务
- Key program of TwinCAT 3 RS232 communication
- 未來已來:雲原生時代
- Dameng database client shielding SQL keyword
- How to synchronize the oak camera?
猜你喜欢

3DE save to Favorites

如何快速定位bug和编写测试用例?

快速掌握 ASP.NET 身份认证框架 Identity - 用户注册

Some journals of C51

Balanced binary tree -- adjusting transformation rules

Blazor University (31) form - Validation

Cloud native architecture (03) - Architecture

Twitter如何去中心化?看看这十个SocialFi项目

存算一体芯片离普及还有多远?听听从业者怎么说 | 对撞派 x 后摩智能

AI自己写代码让智能体进化!OpenAI的大模型有“人类思想”那味了
随机推荐
Application method and operation of Beifu cx9020 (wince 7) controller
倍福嵌入式控制器PLC各型号介绍
Research on std:: move and std:: forward right value reference
Dart异步是怎麼實現
Cloud native architecture (02) - what is cloud native
Float floating point number understanding
Intranet penetration
微信小程序 上传七牛云 laravel
SSM inpatient management system
如何快速定位bug和编写测试用例?
使用Expanded布局时报错The following assertion was thrown during performLayout
php判断当前时间有没有超过几点
Flutter-渲染原理&三棵树详解
TCL华星发布全球首款0.016Hz超低频OLED穿戴设备屏
Larave 数据库备份 定时任务
其实很多人都在学电子
我在华为度过的 “两辈子”(学习那些在大厂表现优秀的人)
面试官:知道 Flutter 生命周期吗?
WPF achieves star effect
Flutter performance optimization