Index.php
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\User;
class Index extends Controller
{
public function index()
{
# 添加一条数据自动写入时间戳
$res = User::create([
'name' => 'imooc',
'password' => md5('imooc')
]);
# 修改name同时改变时间戳
$user = User::get(1);
$user->name = '14546';
$res = $user->save();
# 软删除(设置时间戳)
$res = User::destroy(1);
# 是用这种方式获取不到被软删除的数据
$res = User::get(1);
# 获取包含软删除的数据
$res = User::withTrashed(true)->find(1);
dump($res->getData());
# 获取所有被删除的数据
$res = User::onlyTrashed()->select();
foreach($res as $val){
dump($val->getData());
}
# -----------------------以下去掉true为软删除-------------------------------------
# 真删除
$res = User::destroy(3, true);
# 真删除
$user = User::get(5);
$res = $user->delete(true);
dump($res);
}
}
?>
User.php
<?php
namespace app\index\model;
use think\Model;
use traits\model\SoftDelete;
class User extends Model
{
use SoftDelete;
# 开启时间戳
protected $autoWriteTimestamp = true;
# 修改默认字段名 false代表关闭
protected $createTime = false;
protected $updateTime = 'update_at';
protected $deleteTime = 'delete_at';
}
?>