Correction status:Uncorrected
Teacher's comments:
实例演示闭包实现查询和软删除:
一、模型类源码Students.php----model
<?php namespace app\index\model; use think\Model; use think\model\concern\SoftDelete;//软删除trait方法集 class Students extends Model { use SoftDelete; //设置数据表的名称 protected $table = 'students'; //设置主键,默认就是ID protected $pk = 'id'; //设置删除时间的字段名 protected $deleteTime = 'delete_time'; //设置软删除字段的默认值 protected $defaultSoftDelete = 0; }
点击 "运行实例" 按钮查看在线实例
二、实例演示闭包实现查询
Students.php----controller源码如下:
<?php namespace app\index\controller; use think\Controller; use app\index\model\Students as StudentsModel;//设置模型类的别名 class Students extends Controller { //模型查询 public function query() { //单条记录查询 $students = StudentsModel::get(function($query){ //get返回满足条件的第一条记录 $query->where('sex',0) ->where('grade','>',70); }); echo '性别为男,成绩大于70的人员信息:<br>'; dump($students); echo '<hr>'; //多条记录查询 $students = StudentsModel::all(function($query){ $query->where('age','<',40)->where('grade','>',70); }); // dump($students); foreach ($students as $students) { echo '姓名:'.$students->name.'<br>'; echo '性别:'.$students->sex.'<br>'; echo '年龄:'.$students->age.'<br>'; echo '成绩:'.$students->grade.'<hr>'; } //采用闭包来实现将请求变量注入到闭包条件中 //$this->request 相当于 new \think\facade\Request // $age = $this->request->param('age') ?:70; $grade = $this->request->param('grade') ?:100; $students = StudentsModel::all(function($query) use ($age,$grade){ $query->where('age','<',$age)->where('grade','>',$grade); }); dump($students); } }
点击 "运行实例" 按钮查看在线实例
运行结果图:
三、实例实现软删除功能及软删除的步骤
软删除的步骤:
(1).在表中添加一个字段:删除时间(删除标记):delete_time
(2).在模型类中添加一个属性:$deleteTime = 'delete_time'
(3).在模型中导入软删除的trait类库:SoftDelete
提醒:最新版支持软删除的默认字段值;软删除的记录在普通查询中不可见
2.实例实现软删除功能
<?php namespace app\index\controller; use think\Controller; use app\index\model\Students as StudentsModel;//设置模型类的别名 /医院 * */ class Students extends Controller { public function softDelete() { StudentsModel::destroy(2);//用更新模拟删除,相当于下面两句 // SELECT * FROM `students` WHERE `id` = 2 // UPDATE `students` SET `delete_time` = 1527267743 WHERE `id` = 2 // $res = StudentsModel::where('id','<',4)->select(); // dump($res); //如果想在查询的时候看到已经被删除的记录 // $res = StudentsModel::withTrashed()->where('id','<',4)->select(); // dump($res); //如果想只看被删除的数据 $res = StudentsModel::onlyTrashed()->select(); dump($res); } }
点击 "运行实例" 按钮查看在线实例