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();
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM