/**
* 软删除示例
*/
public function deleteTest(){
//批量软删除
$res=$this->destroy(function ($query){
$query->where([
['user_name','=','占山2']
]);
});
//单个软删除1
$res=$this->destroy(['id'=>14]);
//单个软删除2
$res=$this->destroy(['user_name'=>'占山2']);
//单个软删除3
$res=$this->destroy(14);
print_r($res);
die();
}
/**
* 更新示例需要try cache 包裹
*/
public function addTest(){
//单个新增加(支持时间自动写入)
$data = [
'user_name'=>'你猜'
];
$this->save($data);
//获取自增id
echo $this->id;
//saveAll方法如果数据中包含主键,那么就是更新,不包含主键,就是新增加(支持时间自动写入)
$datas = [
['user_name'=>'你猜','header_img'=>123],
['user_name'=>'你猜2','header_img'=>123],
['user_name'=>'你猜3','header_img'=>123],
];
$this->saveAll($datas);
}
/**
* 更新数据测试
*/
public function updateTest(){
$update['id'] = 1;
$input['role_id'] = 15;
$update['last_login_time'] = time();
if (true){
$update['status'] = 3;
}
$res = $this->update($update,['id'=>1]);
print_r($res);
die();
//支持自动时间写入更新
UserRole::update([
'role_id'=>$input['role_id'],
],['user_id'=>1]);
//不支持自动更新时间
$this->where([
'id'=>14
])->update([
'user_name'=>'你好哈哈',
]);
//单个数据更新
$this->update([
'user_name'=>'你好哈哈',
'id'=>14
]);
//批量数据更新(如果此id没有也不会插入数据)
$date = [
['id'=>12,'user_name'=>'你猜'],
['id'=>23,'user_name'=>'你猜2']
];
$this->saveAll($date);
die();
//特殊更新方法(支持自动时间写入)
$this->update([
'id'=>13,
'login_error_num'=>Db::raw('login_error_num+1')
]);
}
/**
* 查询数据测试
*/
public function selectData(){
//查询单个数据1
$res=$this->select([12,13]);
if ($res){
$res = $res->toArray();
}
//查询单个数据2
$res = $this->where('user_name','你猜')->find();
//查询单个数据3(该方法为错误示范)find方法只能填id值
$res = $this->find([
'user_name'=>'你猜'
]);
halt($res);
//简单的关联查询
$res=$this->find(1);
if ($res){
//user_role 关联方法名
$res->user_role;
}
$res = $res->toArray();
echo "<pre>";
print_r($res);
die();
//多个数据查询(如果没找到数据返回一个空数组)
$res =$this->where('user_name','张山')->select()->toArray();
//多个数据查询(如果没找到数据返回一个空数组)
$res =$this->where([
['id','<>',1]
])->field('')->select()->toArray();
$where[] =['id','<>',1];
$field = 'id';
$res =$this->getDateByIds($where,$field);
halt($res);
}
thinkphp6模型一般使用方法
最新推荐文章于 2024-05-28 17:43:42 发布