本文已参与「新人创作礼」活动,一起开启掘金创作之路。
软删除就是逻辑删除,数据保留单标记上删除状态,一般我们会用删除时间来作为标记,这样标记状态有了,删除时间也有了。
用Laravel 自带的 Eloquent ORM 来实现软删除。
- 首先在数据迁移文件中添加
删除时间字段
./database/migrations/2014_10_12_000000_create_users_table.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->softDeletes()->comment('删除时间');// 默认添加 deleted_at 字段
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
};
-
执行
php artisan migrate运行迁移文件 -
修改对应的数据模型
./app/Models/User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use SoftDeletes;// 开启软删除
protected $guarded = [];// 不可以注入的字段数据,使用create方法才有效
}
- 软删除方法
直接调用delete()方法或者destroy()方法即可
User::destroy($id);
这时候查询的数据自动添加过滤条件
deleted_at = NULL
- 恢复删除
User::onlyTrashed()->where('id', $id)->restore();
- 永久删除
直接删除数据
User::forceDeleted($id);
查询包含已删除的数据
使用 withTrashed()可以查询出包含已删除的数据
User::withTrashed()->get();
只查询已删除的数据
使用 onlyTrashed()可以只查询出已删除的数据
User::onlyTrashed()->get();