thinkphp6模型一般使用方法

/**
 * 软删除示例
 */
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);

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值