1.首先要做一些設(shè)置
首先在模型類中要使用SoftDeletestrait,該trait為軟刪除提供一系列相關(guān)方法,具體可參考源碼Illuminate\Database\Eloquent\SoftDeletes,此外還要設(shè)置$date屬性數(shù)組,將deleted_at置于其中:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class 模型名 extends Model {
use SoftDeletes;
//...其他一些設(shè)置
protected $dates = ['delete_at'];
public $timestamps = false;
}
2.用laravel向相應(yīng)的數(shù)據(jù)庫添加deleted_at字段
php artisan make:migration alter_表名_deleted_at --table=表名
3.此時(shí)在database/migrations文件夾下會(huì)生成一個(gè)相應(yīng)文件,更改如下
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Alter表名DeletedAt extends Migration {
public function up() {
Schema::table('表名', function (Blueprint $table) {
$table->softDeletes();
});
}
...//其它方法
}
再次運(yùn)行命令php artisan migrate ,發(fā)現(xiàn)數(shù)據(jù)庫相應(yīng)的數(shù)據(jù)表中已經(jīng)有delete_at字段了
4.軟刪代碼
我們在控制器中編寫測試代碼
$post = 模型::find(6);
$post->delete();
if($post->trashed()){
echo '軟刪除成功!';
dd($post);
}else{
echo '軟刪除失?。?;
}
那如果想要在查詢結(jié)果中包含軟刪除的記錄呢?可以使用SoftDeletes trait上的withTrashed方法:
$m = 模型::withTrashed()->get();
dd($m);
有時(shí)候我們只想要查看被軟刪除的模型,這也有招,通過SoftDeletes上的onlyTrashed方法即可:
$m = 模型::onlyTrashed()->get();
dd($m);
有時(shí)候我們需要恢復(fù)被軟刪除的模型,可以使用SoftDeletes提供的restore方法:
恢復(fù)單個(gè)模型
$m = 模型::find(6);
$m->restore();
恢復(fù)多個(gè)模型
模型::withTrashed()->where('id','>',1)->restore();
恢復(fù)所有模型
模型::withTrashed()->restore();
恢復(fù)關(guān)聯(lián)查詢模型
$m = 模型::find(6);
$m->history()->restore();
如果模型配置了軟刪除但我們確實(shí)要?jiǎng)h除該模型對應(yīng)數(shù)據(jù)庫表記錄,則可以使用SoftDeletes提供的forceDelete方法:
$m = 模型::find(6);
$m->forceDelete();