PHP Laravel软删除的实现方法介绍

来自:网络
时间:2023-01-03
阅读:

用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();
返回顶部
顶部