laravel5.2软删除

1.做一些设置

  首先在模型类中要使用SoftDeletestrait,该trait为软删除提供一系列相关方法,具体可参考源码Illuminate\Database\Eloquent\SoftDeletes,此外还要设置$date属性数组,将deleted_at置于其中:
    namespace App\Models; 

    use Illuminate\Database\Eloquent\Model; 
    use Illuminate\Database\Eloquent\SoftDeletes; 

    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文件夹下会生成一个相应文件,更改如下
   use Illuminate\Database\Schema\Blueprint; 
    use Illuminate\Database\Migrations\Migration; 

    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 = App\Flight::withTrashed() ->where('account_id', 1) ->get();
 
  //onlyTrashed 方法会只获取已被软删除的模型:
  $flights = App\Flight::onlyTrashed() ->where('airline_id', 1) ->get();
 
  //恢复单个已经被软删除的模型
  $flight = Flight::withTrashed()-find(1); //这里要注意如果被软删除直接find是查不到的
  $flight->restore();

  //恢复多个模型
  App\Flight::withTrashed() ->where('airline_id', 1) ->restore();
 
  // 强制删除单个模型实例...
  $flight->forceDelete();

  // 强制删除所有相关模型...
  $flight->history()->forceDelete();
 
 
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/jorzy/p/9916728.html