軟刪除
軟刪除
| 版本 | 調(diào)整功能 |
|---|---|
| 5.0.2 |
deleteTime 屬性改為非靜態(tài)定義 |
在實際項目中,對數(shù)據(jù)頻繁使用刪除操作會導致性能問題,軟刪除的作用就是把數(shù)據(jù)加上刪除標記,而不是真正的刪除,同時也便于需要的時候進行數(shù)據(jù)的恢復。
要使用軟刪除功能,需要引入SoftDelete trait,例如User模型按照下面的定義就可以使用軟刪除功能:
namespace app\index\model;
use think\Model;
use traits\model\SoftDelete;
class User extends Model
{
use SoftDelete;
protected $deleteTime = 'delete_time';
}
5.0.2版本之前deleteTime屬性必須使用static定義。
deleteTime屬性用于定義你的軟刪除標記字段,ThinkPHP5的軟刪除功能使用時間戳類型(數(shù)據(jù)表默認值為Null),用于記錄數(shù)據(jù)的刪除時間。
可以用類型轉(zhuǎn)換指定軟刪除字段的類型,建議數(shù)據(jù)表的所有時間字段統(tǒng)一一種類型。
定義好模型后,我們就可以使用:
// 軟刪除
User::destroy(1);
// 真實刪除
User::destroy(1,true);
$user = User::get(1);
// 軟刪除
$user->delete();
// 真實刪除
$user->delete(true);
默認情況下查詢的數(shù)據(jù)不包含軟刪除數(shù)據(jù),如果需要包含軟刪除的數(shù)據(jù),可以使用下面的方式查詢:
User::withTrashed()->find();
User::withTrashed()->select();
如果僅僅需要查詢軟刪除的數(shù)據(jù),可以使用:
User::onlyTrashed()->find();
User::onlyTrashed()->select();
如果你的模型定義了
base基礎(chǔ)查詢,請確保添加軟刪除的基礎(chǔ)查詢條件。
文檔最后更新時間:2018-04-26 10:06:47
← 只讀字段
類型轉(zhuǎn)換 →
未解決你的問題?請到「問答社區(qū)」反饋你遇到的問題
