批改状态:未批改
老师批语:
在thinkphp中模型与Db类不一样,
1,Db只负责数据表的访问
2,模型是业务数据和业务逻辑的完美封装
3,Db是模型的基础,模型最终是依赖Db来实现的
4,Db返回的是数组,模型返归的是对象 (dump是框架提供的方法->数组;\var_dump全局函数->对象)
软删除
* 1,在表中添加一个字段:删除时间:delete_time
* 2,在模型类添加一个属性:$deleteTime ='delete_time'
* 3,在模型中导入软删除的trait类库:SoftDelete
* 4,最小版支持设置软删除的默认字段值
准备工作:
命令行:cd到安装目录php think make:model index/Staff 创建 staff模型,引入think\Model,并创建一个staff子类继承这个 Model(因为这里的操作表格是数据库里的staff表),需设置表格名称和关键字;软删除需另外引入SoftDelete并复制到子类中,设置删除时间的字段名和设置软删除的字段名
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';
//设置主键,默认id
protected $pk = 'staff_id';
//设置删除时间的字段名
protected $deleteTime = 'delete_time';
//设置软删除的字段名
protected $defaultSoftDelete = 0;
}闭包实现查询
<?php
namespace app\index\controller;
use think\Controller; //继承系统控制器
use app\index\model\Staff as StaffModel;//设置模型类的别名
class Staff extends Controller //继承基类控制器
{
public function query()
{
//用闭包来实现降请求变量注入到闭包条件中
$this->request = new\think\facade\Request //当前控制器里有一个request请求对象
$age = $this->request->param('age') ?: 40;
$salary = $this->request->param('salary') ?: 4000;
$staffs = StaffModel::all(function($query) use ($age) {
$query->where('age','>',$age)->where('salary','>',4000);
});
foreach ($staffs as $staff) {
echo '姓名:'.$staff->name.'<br>';
echo '年龄:'.$staff->age.'<br>';
echo '工资:'.$staff->salary.'<hr>';
}
}//查询当前年龄大于40 工资小于4000的人员软删除的实现
原理:用更新操作给需要删除的数据添加一个删除时间,平常查询不会显示,显示需调用withTrashed()/onlyTrashed()方法
public function softDelete()
{
StaffModel::destroy(1);
//UPDATE `staff` SET `delete_time` = 1527238503 WHERE `staff_id` = 1
StaffModel::update( //软删除删除,实际上对时间戳进行更新为0
['delete_time'=>0],
['staff_id'=>1]
);
// $res = StaffModel::where('staff_id < 5')->select();
//回收站的内容也显示出来
// $res = StaffModel::withTrashed()->where('staff_id < 5')->select();
// 只看回收站
$res = StaffModel::onlyTrashed()->select();
dump($res);
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号