TP5.0以上数据库增加数据异常

在tp5.0以上版本使用的时候对数据库数据增加的时候类似重复提交同一唯一字段返回的不是我们想要的false或者0,而是直接异常抛出了,这时候我们使用以下的解决方法

//tp5以上的新增数据失败并不能返回一些值,只能通过use think\Exception;然后在增加操作的时候进行try catch异常抛出,在model层这样写最为保险
                // try {
                //     $res1 = $this->save($data['users'][0]);
                
                //     $res2 = $this->save($data['users'][1]);
                // } catch (Exception $e) {
                //     return $e->getMessage();
                // }
controller层使用               
    $res = $ffcsuser->$action('18520638666660',$data);
        if($res == 1){
            $result = [
                'status'    => 200,
                'msg'       => '用户操作成功'
            ];  
        }else{
            $result = [
                'status'    => 444,
                'msg'       => $res
            ]; 

        }


方法之二就是去改动底层文件

edit file: thinkphp\library\think\db\Builder.php 

public function insert ...

  1. $replace ? 'REPLACE' : 'INSERT',改为以下$replace ? ($replace === 'IGNORE' ? 'INSERT IGNORE'  : 'REPLACE') : 'INSERT',

猜你喜欢

转载自blog.csdn.net/hoewang/article/details/80709483
今日推荐