• laravel5.2总结--软删除


      当模型被软删除时,它们并不会真的从数据库中被移除。而是会在模型上设置一个 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();
     
     
  • 相关阅读:
    css 样式 图片平铺整个界面
    div垂直居中 css div盒子上下垂直居中
    .net 日期格式转换
    一个DIV三列布局100%高度自适应的好例子(国外)
    TFS2012团队管理基本配置及基础使用方法
    转-CSS3 圆角(border-radius)
    webpack进阶用法你都get到了么?
    webpack4的配置你都掌握了么?
    初入webpack
    番外篇:一篇读懂浏览器结构
  • 原文地址:https://www.cnblogs.com/redirect/p/6177915.html
Copyright © 2020-2023  润新知