• laravel框架总结(九) -- 软删除


     当模型被软删除时,它们并不会真的从数据库中被移除。而是会在模型上设置一个 deleted_at 属性并将其添加到数据库。如果对应模型被软删除,则deleted_at字段的值为删除时间,否则该值为空。

     

    1.做一些设置

      首先在模型类中要使用SoftDeletestrait,该trait为软删除提供一系列相关方法,具体可参考源码IlluminateDatabaseEloquentSoftDeletes,此外还要设置$date属性数组,将deleted_at置于其中:
    <?php 
        namespace AppModels; 
    
        use IlluminateDatabaseEloquentModel; 
        use IlluminateDatabaseEloquentSoftDeletes; 
    
        class Post extends Model { 
            use SoftDeletes;
            //...其他一些设置 
            protected $dates = ['delete_at']; 
        }    

    2.向数据库中的相应数据表添加delete_at字段

      1>这里我们使用数据迁移来实现
      php artisan make:migration alter_posts_deleted_at --table=posts
     
      2>此时在database/migrations文件夹下会生成一个相应文件,更改如下
    <?php 
        use IlluminateDatabaseSchemaBlueprint; 
        use IlluminateDatabaseMigrationsMigration; 
    
        class AlterPostsDeletedAt extends Migration { 
            /** 
            * Run the migrations. 
            * 
            * @return void 
            */ 
            public function up() { 
                Schema::table('posts', function (Blueprint $table) { 
                    $table->softDeletes(); 
                }); 
            } 
            ...//其它方法 
        }                
      3>再次运行命令 php artisan migrate ,发现数据库相应的数据表中已经有delete_at字段了
     

    3.使用方法

      在模型上调用 delete 方法时,deleted_at 字段将会被设置成目前的日期和时间。而且,当查找有启用软删除的模型时,被软删除的模型将会自动从所有查找结果中排除。
      //在模型上调用delete方法
      $post = Post::find(6); $post->delete();
      //要确认指定的模型实例是否已经被软删除,可以使用 trashed 方法:      if($post->trashed()){     echo '软删除成功!';     dd($post);   }else{     echo '软删除失败!';   }   //查找被软删除的模型   $flights = AppFlight::withTrashed() ->where('account_id', 1) ->get();   //onlyTrashed 方法会只获取已被软删除的模型:   $flights = AppFlight::onlyTrashed() ->where('airline_id', 1) ->get();   //恢复单个已经被软删除的模型   $flight = Flight::withTrashed()-find(1); //这里要注意如果被软删除直接find是查不到的   $flight->restore();   //恢复多个模型   AppFlight::withTrashed() ->where('airline_id', 1) ->restore();   // 强制删除单个模型实例...   $flight->forceDelete();   // 强制删除所有相关模型...   $flight->history()->forceDelete();
  • 相关阅读:
    SQL语句优化(转)
    ConcurrentHashMap源码分析
    centos 上安装gearman
    从与UCenter集成的过程中,看到Discuz的不开放
    UCenter实现同步登陆
    讨人喜欢的 MySQL replace into 用法(insert into 的增强版)
    Truncate Table
    mysql中key 、primary key 、unique key 与index区别
    PHP登录时限
    用Fragment实现如新浪微博一样的底部菜单的切换
  • 原文地址:https://www.cnblogs.com/ghjbk/p/6638125.html
Copyright © 2020-2023  润新知