3-9 模型時(shí)間戳+軟刪除
2018-05-08
軟刪除:
首先在模型里面引用SoftDelete<?php namespace?app\index\model; use?think\Model; use?traits\model\SoftDelete; class?User?extends?Model{ ????use?SoftDelete; ????#autowritetimestamp表示創(chuàng)建與更新的時(shí)間戳都被打開 ????protected?$autoWriteTimestamp?=?true; ????#刪除數(shù)據(jù)的時(shí)候刪除時(shí)間戳默認(rèn)寫入字段delete_time中,當(dāng)要自定義時(shí): //????protected?$deleteTime?=?'自定義刪除時(shí)間字段名'; }
然后在控制器里面執(zhí)行操作
<?php namespace?app\index\controller; use?think\Controller; use?app\index\model\User; class?Index?extends?Controller { ????public?function?index(){ //????????$res?=?User::destroy(4);//被軟刪除 //????????$res?=?User::get(2);//返回NULL ????????#查詢包含已刪除的數(shù)據(jù) ????????//$res?=?User::withTrashed(true)->find(2); ????????#查詢僅包含已刪除的數(shù)據(jù) ????????$res?=?User::onlyTrashed()->select(); ????????foreach?($res?as?$val){ ????????????dump($val); ????????} ????????#若要恢復(fù)被軟刪除的數(shù)據(jù),直接用update方式將delete_time的值設(shè)置為NULL即可 ????????#當(dāng)開啟軟刪除后要想真正徹底刪除數(shù)據(jù),在destroy的第二個(gè)參數(shù)后面?zhèn)魅胍粋€(gè)true值 ????????$res?=?User::destroy(1,true); ????????#通過(guò)get方式進(jìn)行軟刪除/刪除 ????????$res?=?User::get(3);//如果此處數(shù)據(jù)已經(jīng)被軟刪除則獲取到的為NULL,后面的操作無(wú)效 ????????$user->delete();//軟刪除 ????????$res?=?$user->delete(true);//刪除 ????} }
1
采集 1
舉報(bào)
0/150
提交
取消