W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
除了真實(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()) {
//
}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: