Thinkph5——模型軟刪除


在實際項目中,對數據頻繁使用刪除操作會導致性能問題,軟刪除的作用就是把數據加上刪除標記,而不是真正的刪除,同時也便於需要的時候進行數據的恢復。

第一步:在數據庫添加字段“delete_time”

字段類型可以是datetime,也可以是int(版本Tp5.0最好使用int);同時它的默認值必須為null

注意:版本為Thinkph5,數據庫字段“delete_time”類型最好int;如果類型是datetime,它的值就變成了"0000-00-00 00:00:00"。Thinkphp5.1沒有這個問題,這應該是版本的問題。

 

第二步:要使用軟刪除功能,需要引入SoftDelete

<?php
namespace app\index\model;
use think\Model;
use traits\model\SoftDelete;

class Shopping extends Model     //購物車
{
    use SoftDelete;
    protected $deleteTime = 'delete_time';
}

我們在調用模型查詢,它自動加上where把已經軟刪除的過濾掉

 

第三步:使用軟刪除

//軟刪除
Shopping::destroy(1);//這里輸入值它的id;成功就返回1
//真實刪除
Shopping::destroy(1,true);
$shopping = Shopping::get(1); //軟刪除 $shopping->delete(); //真實刪除 $shopping->delete(true);

如果你想自己寫,使用useSoftDelete給delete_time賦值

//使用useSoftDelete給的delete_time賦值
Shopping::whereIn('id',[10,12])->useSoftDelete('delete_time', date("Y-m-d H:i:s",time()))->delete();

默認情況下查詢的數據不包含軟刪除數據,如果需要包含軟刪除的數據,可以使用下面的方式查詢:

Shopping::withTrashed()->find();
Shopping::withTrashed()->select();//查詢全部數據,包括軟刪除

如果僅僅需要查詢軟刪除的數據,可以使用:

Shopping::onlyTrashed()->find();
Shopping::onlyTrashed()->select();

回復軟刪除數據:

//獲取已經被軟刪除的數據
$del = Shopping::onlyTrashed()->where(['id'=>1,'name'=>"lhs"])->find();
//回復軟刪除
$del->restore();

注意:如果你的模型定義了base基礎查詢,請確保添加軟刪除的基礎查詢條件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM