3-9 模型時間戳+軟刪除
2018-05-08
軟刪除:
首先在模型里面引用SoftDelete<?php namespace?app\index\model; use?think\Model; use?traits\model\SoftDelete; class?User?extends?Model{ ????use?SoftDelete; ????#autowritetimestamp表示創建與更新的時間戳都被打開 ????protected?$autoWriteTimestamp?=?true; ????#刪除數據的時候刪除時間戳默認寫入字段delete_time中,當要自定義時: //????protected?$deleteTime?=?'自定義刪除時間字段名'; }
然后在控制器里面執行操作
<?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 ????????#查詢包含已刪除的數據 ????????//$res?=?User::withTrashed(true)->find(2); ????????#查詢僅包含已刪除的數據 ????????$res?=?User::onlyTrashed()->select(); ????????foreach?($res?as?$val){ ????????????dump($val); ????????} ????????#若要恢復被軟刪除的數據,直接用update方式將delete_time的值設置為NULL即可 ????????#當開啟軟刪除后要想真正徹底刪除數據,在destroy的第二個參數后面傳入一個true值 ????????$res?=?User::destroy(1,true); ????????#通過get方式進行軟刪除/刪除 ????????$res?=?User::get(3);//如果此處數據已經被軟刪除則獲取到的為NULL,后面的操作無效 ????????$user->delete();//軟刪除 ????????$res?=?$user->delete(true);//刪除 ????} }
1
采集 1
舉報
0/150
提交
取消