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

4986 10
黑夜隐士 2022-11-9 14:25:32 | 显示全部楼层 |阅读模式
用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();到此这篇关于PHP Laravel软删除的实现方法介绍的文章就介绍到这了,更多相关PHP Laravel软删除内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行