批改状态:未批改
老师批语:
一、模型基本操作
1.模型是一个继承自框架的think\Model.php的类;
2.模型大多数情况下与一张数据表对应;
3.模型支持对象关系映射;
4.模型对应数据表,而模型实例(对象)对应表中的一条记录
用模型的方法实现对数据表的增删改查:get()单记录查询,all()多记录查询,create()新增,update()更新,destroy()删除
二、软删除
1,在数据表中添加delete_time int(10)字段,保存删除时间(删除标记);
2,在模型中导入软操作类,use think\model\concern\SoftDelete;
3,在模型中设置软删除字段名及默认值,$deleteTime = 'delete_time',$defaultSoftDelete = 0;
软删除的数据在普通查询中不可见
withTrashed()方法可以使软删除的数据包含在查询结果中
onlyTrsashed()方法则只查询软删除的数据
onlyTrashed()->restore()方法可以恢复被软删除(加了删除标记)的记录
模型类代码(app\index\model\Kc.php)
<?php
namespace app\index\model;
use think\Model;
use think\model\concern\SoftDelete;
class Kc extends Model
{
use SoftDelete;
protected $table = 'kc'; //设置书库表名
protected $pk = 'kc_id'; //设置主键
protected $deleteTime = 'delete_time'; //设置删除标记字段(删除时间)
protected $defaultSoftDelete = 0; //设置删除标记字段默认值
}点击 "运行实例" 按钮查看在线实例
模型操作代码(app\index\controller\Kc.php)
<?php
namespace app\index\controller;
use think\Controller;
use app\index\model\Kc as KcModel;
//模型管理数据表
class Kc extends Controller
{
//模型查询多条记录,利用回调函数传参(闭包)
public function query(){
$kcs = KcModel::all(function($query){
$query->where('dj','<',500)->where('cd','济南');
});
echo '查询kc表中单价小于500,产地是济南的商品<br>';
dump($kcs);
}
//模型删除
public function delete(){
KcModel::destroy(function($query){
$query->where('mc','气缸体');
});
}
//软删除验证
public function softDelete(){
//软删除的记录不会出现在普通查询结果中
$res = KcModel::where('dj','>',3000)->select();
dump($res);
//查询结果不排除软删除的记录
$res1 = KcModel::withTrashed()->Where('dj','>',3000)->select();
dump($res1);
//只查询软删除的记录
$res2 = KcModel::onlyTrashed()->select();
dump($res2);
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号