美文网首页
Laravel6.X软删除教程

Laravel6.X软删除教程

作者: 前端组件库 | 来源:发表于2020-02-22 22:46 被阅读0次

    软删除的意思就是没有真正删除,只是在数据库里标记了一下,便于随时恢复。我们可以软删除用户,让他失去正常的权限,也可以随时恢复正常的权限。我们可以软删除文章放到所谓的垃圾桶里,随时可以再恢复。

    为了讲解这一教程,我做了一些准备工作,创建了一个模型文件Post, 并且增加了 protected $guarded = [], 使得关掉了mass assignment。并且创建了一个migration文件,为了填充假数据,里面只加了2个字段,title和body。做了一个控制器,做了一个index方法。

    Post迁移代码:

    public function up()
        {
            Schema::create('posts', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('title');
                $table->text('body');
                $table->timestamps();
            });
        }
    

    1. 填充假数据

    php artisan tinker
    factory(\App\Post::class,20)->create();
    

    2.控制器里的index方法

    public function index()
    {
       $posts = Post::all();
       return view('/', compact("posts"));
    }
    

    3.添加一个字段"deleted_at"到这个Post模型。

    php artisan make:migration add_deleted_at_column_to_posts --table posts
    

    我们来看看迁移文件:

    public function up()
        {
            Schema::table('posts', function (Blueprint $table) {
                //
            });
        }
    

    我们把它修改成:

    public function up()
        {
            Schema::table('posts', function (Blueprint $table) {
                $table->timestamp("deleted_at")->nullable();
            });
        }
    
    
    public function down()
        {
            Schema::table('posts', function (Blueprint $table) {
                $table->dropColumn('deleted_at');
            });
        }
    

    再执行一下迁移文件:

    php artisan migrate
    

    这样我们就增加了一个字段在posts表上。

    4. 修改模型文件添加softdelete。

    在模型文件头部引入之后,现在的模型文件是这样的:

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Post extends Model
    {
        use SoftDeletes;
    
        protected $guarded = [];
    }
    

    5.测试软删除

    我们可以直接在tinker里面测试软删除。

    php artisan tinker
    

    假若我们想软删除第一个记录,那么我们就执行如下命令:

    $post = \App\Post::where('id',1)->first();
    $post->delete();
    

    跟我们一般的删除是一样的,但是你如果查一下数据库的话,就会发现,记录并没有删除,那么我们如何才能查到这个记录呢?

    \App\Post::where('id',1)->withTrashed()->first();
    

    如果我们想恢复一下,如何做呢?

    \App\Post::where('id',1)->withTrashed()->first()->restore();
    

    如果我们想真正删除这个记录,该如何做呢?

    \App\Post::where('id',1)->withTrashed()->first()->forceDelete();
    

    相关文章

      网友评论

          本文标题:Laravel6.X软删除教程

          本文链接:https://www.haomeiwen.com/subject/mxglqhtx.html