thinkPHP5.0模型实现软删除
Login.php
<?php
namespace app\index\controller;
use think\Controller;
use Gregwar\Captcha\CaptchaBuilder;
use think\Loader;
use app\index\model\Data;
use think\Db;
class Login extends Controller
{
public function _initialize()
{
//parent::__construct();
$this->data = Loader::model('data');
}
public function delData()
{
//删除id=16的记录
$res = Data::destroy(16);
//返回int(1)受影响记录数量
dump($res);
}
//删除后进行查询验证
public function selData()
{
//返回为null,表示删除成功
//dump(Data::get(16));
$res = Data::select();
foreach ($res as $k => $v) {
//getData()函数可以获取对象里面的数据
dump($v->getData());
}
}
//默认情况下,查询到的数据不包含软删除数据,如果需要包含软删除的数据
public function selData1()
{
//查询单条数据
$res = Data::withTrashed(true)->find();
dump($res->getData());
//查询多条数据
$res = Data::withTrashed(true)->select();
foreach ($res as $k => $v) {
dump($v->getData());
}
}
//如果只想删除软删除的数据,相当于查看回收站
public function selData2()
{
//单条数据
$res = Data::onlyTrashed(true)->find();
dump($res->getData());
//多条数据
$res = Data::onlyTrashed(true)->select();
foreach ($res as $key => $val) {
dump($val->getData());
}
}
//恢复软删除记录
//控制器中将被软删除的delete_time更新为null即可
public function selData3()
{
$res = Data::update([
'delete_time' => null,
], ['id' => 16]);
dump($res);
//现在就可以获取重新被软删除的记录了
$res = Data::get(16);
dump($res->getData());
}
//物理删除是指彻底将该记录从表中移除,不可恢复。给destroy()方法传入第二个参数true
public function delReal()
{
//删除id为16的记录
$res = Data::destroy(16, true);
dump($res);
//使用delete(true)实现物理删除
$res = Data::where('id', 18)->delete();
dump($res);
}
}
Data.php
<?php
namespace app\index\model;
use think\Db;
use think\Model;
use traits\model\SoftDelete;
class Data extends Model
{
//在当前类导入,就可以使用其中的方法啦
use SoftDelete;
//如果你的字段名为框架默认的delete_time,可省略
protected $deleteTime = 'delete_time';
protected $table = 'bbs_data';
public function getMenu()
{
$res = Db::name($this->table)->select();
return $res;
}
}