Laravel軟刪除

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();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容