//模型类 model\Staff.php
<?php
namespace app\index\model;
use think\Model;
use think\Model\concern\SoftDelete; //trait方法集
class Staff extends Model
{
use SoftDelete;
protected $table = 'staff';
protected $pk = 'staff_id';
//设置删除时间的字段名
protected $delete_time = 'delete_time';
//设置软删除字段的默认值
// protected $defaultSoftdelete = 0;
}
//控制类 controller\Staff.php
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Staff as StaffModel;
use think\Db;
class Staff extends Controller
{
//模型查询 get(主键/闭包) all(主键/闭包)
public function query()
{
$res = StaffModel::all(function ($query){
$query->where('staff_id','<',10)->where('sex',1);
});
dump($res);
}
public function softDelete()
{
/*步骤:
* 1、在表中增加字段:delete_time(作为删除标志):protected $delete_time = 'delete_time';
* 2、模型类文件需引入软删除的trait类: use think\model\concern\SoftDelete
* 3、在模型类内还需 use SoftDelete;
*/
//当数据表中没有delete_time字段,则先添加
$sql = "ALTER TABLE `staff` ADD delete_time INT NOT NULL DEFAULT 0"; //增加字段
$sql2 = "select * from `staff` where delete_time is null"; //判断某字段是否空
if (Db::table('staff')->query($sql2)) {
Db::table('staff')->execute($sql);
}
$res = StaffModel::destroy(2); // UPDATE `staff` SET `delete_time` = 1527235261 WHERE `staff_id` = 2
return $res? '成功删除': '删除失败';
}
}