Laravel 8 軟刪除

2021-07-19 11:31 更新

除了真實(shí)刪除數(shù)據(jù)庫記錄,Eloquent 也可以「軟刪除」模型。軟刪除的模型并不是真的從數(shù)據(jù)庫中刪除了。 事實(shí)上,是在模型上設(shè)置了 deleted_at 屬性并將其值寫入數(shù)據(jù)庫。如果 deleted_at 值非空,代表這個(gè)模型已被軟刪除。如果要開啟模型軟刪除功能,你需要在模型上使用 Illuminate\Database\Eloquent\SoftDeletes trait:

<?php

namespace App\Models;

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

class Flight extends Model
{
    use SoftDeletes;
} 

技巧:SoftDeletes 會(huì)自動(dòng)將 deleted_at 屬性轉(zhuǎn)換成 DateTime / Carbon 實(shí)例。

當(dāng)然,你需要把 deleted_at 字段添加到數(shù)據(jù)表中。Laravel數(shù)據(jù)遷移 有創(chuàng)建這個(gè)字段的方法:

public function up()
{
    Schema::table('flights', function (Blueprint $table) {
        $table->softDeletes();
    });
}

public function down()
{
    Schema::table('flights', function (Blueprint $table) {
        $table->dropSoftDeletes();
    });
} 

那現(xiàn)在,當(dāng)你在模型實(shí)例上使用 delete 方法,當(dāng)前日期時(shí)間會(huì)寫入 deleted_at 字段。同時(shí),查詢出來的結(jié)果也會(huì)自動(dòng)排除已被軟刪除的記錄。

你可以使用 trashed 方法來驗(yàn)證給定的模型實(shí)例是否已被軟刪除:

if ($flight->trashed()) {
    //
} 


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)