laravel5.2總結--軟刪除

  當模型被軟刪除時,它們並不會真的從數據庫中被移除。而是會在模型上設置一個 deleted_at 屬性並將其添加到數據庫。若是對應模型被軟刪除,則deleted_at字段的值爲刪除時間,不然該值爲空。
 

1.作一些設置

  首先在模型類中要使用SoftDeletestrait,該trait爲軟刪除提供一系列相關方法,具體可參考源碼Illuminate\Database\Eloquent\SoftDeletes,此外還要設置$date屬性數組,將deleted_at置於其中:
<?php 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文件夾下會生成一個相應文件,更改以下
<?php 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();
相關文章
相關標籤/搜索