YII2.0 数据库增删改查

Posted 一个人的孤独自白

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了YII2.0 数据库增删改查相关的知识,希望对你有一定的参考价值。

/*==================== dkhBaseModel 数据库增删改查方法 start ================================*/
    //新增一条数据
    public function baseInsertData($data){
        if(!is_array($data)) {return $this->setError([‘errmsg‘=>‘data Error‘]);};
        $db = \Yii::$app->db;
        $ok = $db->createCommand()->insert($this->tableName(), $data)->execute();
        if($ok){
            //返回自增id
            return $db->getLastInsertID();
        }else{
            return $this->setError([‘errmsg‘=>‘插入记录失败‘]);
        }
    }

    //通过条件查询一条记录
    public function baseGetOne($condition = [],$orderBy = ‘id DESC‘,$select = array()){
        //$condition 搜索条件 如:$condition = [‘and‘];$condition[] = [‘=‘,‘id‘,1];$condition[] = [‘LIKE‘,‘name‘,‘dkh‘];
        //$select 字段过滤 如: [‘id‘,‘field1‘,‘field2‘]
        return $this->find()->select($select)->where($condition)->orderBy($orderBy)->asArray()->one();
    }

    //通过条件查询一条关联模型记录
    public function baseGetOneRelation($condition = [],$tables,$orderBy = ‘‘,$select = array()){
        return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->asArray()->one();
    }

    //获取全部数据
    public function baseGetAll($condition = [],$orderBy = ‘id DESC‘,$select = array()){
        return $this->find()->select($select)->where($condition)->orderBy($orderBy)->asArray()->all();
    }

    //通过条件查询多条关联模型记录
    public function baseGetAllRelation($condition = [],$tables,$orderBy = ‘‘,$select = array()){
        return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->asArray()->all();
    }

    //根据id删除一条数据
    public function baseDeleteById($id){
        $this->id = $id;
        return $this->findOne($id)->delete();

    }

    //删除指定条件的数据
    public function baseDeleteAll($condition = []){
        if(empty($condition)) {return $this->setError([‘errmsg‘=>‘deleteAll Error‘]);};
        return $this->deleteAll($condition);
    }

    //执行原生sql语句,一般用于更新,批量新增,删除数据
    public function baseExecuteSql($sql){
        $db = \Yii::$app->db;
        //在调用的地方做执行是否成功的判断
        return $db->createCommand($sql)->execute();
    }


    //执行原生sql语句,一般用于查询数据 返回单行
    public function baseQueryOneSql($sql){
        $db = \Yii::$app->db;
        return $db->createCommand($sql)->queryOne();
    }

    //执行原生sql语句,一般用于查询数据 返回多行
    public function baseQueryAllSql($sql){
        $db = \Yii::$app->db;
        return $db->createCommand($sql)->queryAll();
    }

    //通过主键查询一条记录
    public function baseGetOneByid($id){
        $model =  $this->findOne($id);
        if($model){
            return $model->attributes;
        }else{
            return array();
        }
    }

    //更新符合条件的数据
    public function baseUpdateData($data,$condition = []){
        if(empty($condition)) {return $this->setError([‘errmsg‘=>‘condition Empty‘]);};
        $res = $this->updateAll($data,$condition);
        if($res === false){
            return $this->setError([‘errmsg‘=>‘更新失败‘]);
        }
        return $res;
    }

    //获取分页数据
    public function basePageData($condition = [],$page,$pageSize,$orderBy = ‘id DESC‘,$select = array()){
        //$page,$pageSize   相当于 LIMIT $page,$pageSize
        //$select 过滤字段 [‘id‘,‘field1‘,‘field2‘]
        return $this->find()->select($select)->where($condition)->offset($page)->limit($pageSize)->orderBy($orderBy)->asArray()->all();
    }


    //获取分页数据 并且 关联模型记录
    public function basePageDataRelation($condition = [],$page,$pageSize,$tables,$orderBy = ‘‘,$select = array()){
        //$page,$pageSize  相当于SQL语句 LIMIT $page,$pageSize
        //$select 字段过滤 如: [‘id‘,‘field1‘,‘field2‘]
        //$tables 关联模型表 如: [‘table1‘,‘table2‘]
        return $this->find()->joinWith($tables)->select($select)->where($condition)->orderBy($orderBy)->offset($page)->limit($pageSize)->asArray()->all();
    }

    //通过条件查询记录条数
    public function baseGetCount($condition = [],$select = array()){
        return $this->find()->select($select)->where($condition)->count();
    }

    //通过条件查询记录条数 并且 关联模型
    public function baseGetCountRelation($condition = [],$tables,$select = array()){
        return $this->find()->joinWith($tables)->select($select)->where($condition)->count();
    }




    //通过条件查询一条记录
    public function baseModelGetOne($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        return $this->find()->select($field)->where($condition)->orderBy($order)->asArray()->one();
    }

    //通过条件查询一条关联模型记录
    public function baseModelGetOneRelation($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        if(isset($params[‘join‘]) && is_array($params[‘join‘])  && !empty($params[‘join‘])){
            $join = $params[‘join‘];
        }else{
            $join = ‘‘;
        }
        return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->asArray()->one();
    }


    //获取全部数据
    public function baseModelGetAll($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        return $this->find()->select($field)->where($condition)->orderBy($order)->asArray()->all();
    }

    //通过条件查询多条关联模型记录
    public function baseModelGetAllRelation($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        if(isset($params[‘join‘]) && is_array($params[‘join‘])  && !empty($params[‘join‘])){
            $join = $params[‘join‘];
        }else{
            $join = ‘‘;
        }
        return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->asArray()->all();
    }



    //获取分页数据
    public function baseModelPageData($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        if(isset($params[‘page‘])){
            $page = $params[‘page‘];
        }else{
            $page = 0;
        }
        if(isset($params[‘pageSize‘])){
            $pageSize = $params[‘pageSize‘];
        }else{
            $pageSize = 10;
        }
        return $this->find()->select($field)->where($condition)->offset($page)->limit($pageSize)->orderBy($order)->asArray()->all();
    }


    //获取分页数据 并且 关联模型记录
    public function baseModelPageDataRelation($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘order‘])  && !empty($params[‘order‘])){
            $order = $params[‘order‘];
        }else{
            $order = ‘id DESC‘;
        }
        if(isset($params[‘join‘]) && is_array($params[‘join‘])  && !empty($params[‘join‘])){
            $join = $params[‘join‘];
        }else{
            $join = ‘‘;
        }
        if(isset($params[‘page‘])){
            $page = $params[‘page‘];
        }else{
            $page = 0;
        }
        if(isset($params[‘pageSize‘])){
            $pageSize = $params[‘pageSize‘];
        }else{
            $pageSize = 10;
        }
        return $this->find()->joinWith($join)->select($field)->where($condition)->orderBy($order)->offset($page)->limit($pageSize)->asArray()->all();
    }

    //通过条件查询记录条数
    public function baseModelGetCount($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        return $this->find()->select($field)->where($condition)->count();
    }

    //通过条件查询记录条数 并且 关联模型
    public function baseModelGetCountRelation($params){
        if(isset($params[‘condition‘]) && is_array($params[‘condition‘]) && !empty($params[‘condition‘])){
            $condition = $params[‘condition‘];
        }else{
            $condition = [];
        }
        if(isset($params[‘field‘]) && is_array($params[‘field‘]) && !empty($params[‘field‘])){
            $field = $params[‘field‘];
        }else{
            $field = [];
        }
        if(isset($params[‘join‘]) && is_array($params[‘join‘])  && !empty($params[‘join‘])){
            $join = $params[‘join‘];
        }else{
            $join = ‘‘;
        }
        return $this->find()->joinWith($join)->select($field)->where($condition)->count();
    }



    //删除指定条件的数据
    public function baseModelDeleteAll($params){
        if(empty($params[‘condition‘])) {return $this->setError([‘errmsg‘=>‘deleteAll Error‘]);};
        return $this->deleteAll($params[‘condition‘]);
    }

    //更新符合条件的数据
    public function baseModelUpdateData($params){
        if(empty($params[‘condition‘])) {return $this->setError([‘errmsg‘=>‘condition is Empty‘]);};
        $res = $this->updateAll($params[‘data‘],$params[‘condition‘]);
        if($res === false){
            return $this->setError([‘errmsg‘=>‘更新失败‘]);
        }
        return $res;
    }

 增删改查使用方法:

                //选择分组
                $condition = [‘and‘];
                $condition[] = [‘=‘,‘member.shop_id‘,$params[‘shop_id‘]];
                $condition[] = [‘IN‘,‘member.member_group_id‘,$params[‘member_tag‘][‘groups‘]];  //索引数组
                $wshMemberModel = new WshMember();
                $memberList = $wshMemberModel->baseGetAllRelation($condition,[‘wxUserInfos‘],‘member.id DESC‘,[‘member.id‘]);

 

$wshWxUsersModel = new WshWxUsers();
                $userList = $wshWxUsersModel->baseGetAll([‘shop_id‘=>$params[‘shop_id‘],‘user_id‘=>$uid],‘id DESC‘,[‘user_id‘,‘open_id‘]);

 

$insertData = [
            ‘material_id‘=>isset($params[‘material_id‘])?$params[‘material_id‘]:0,
            ‘shop_id‘=>$params[‘shop_id‘],
            ‘shop_sub_id‘=>$_SESSION[‘_staff‘][‘shop_sub_id‘],
            ‘send_time‘=>$now,
            ‘send_type‘=>$params[‘send_type‘],
            ‘text_content‘=>$params[‘text_content‘],
            ‘sort_content‘=>$params[‘sort_content‘],
        ];

        $insertId = $wshWxMessageSendMutilModel->baseInsertData($insertData);

 

            $dkhWxMessageMemberMutilModel = new DkhWxMessageMemberMutil();
            $successValues = ‘‘;$successSql = ‘‘;
            //组装sql语句
            foreach($successList as $item){
                $successValues .= "(‘{$insertId}‘,‘{$item[‘user_id‘]}‘,‘1‘,‘{$now}‘,‘{$now}‘),";
            }
            if(!empty($successValues)) {
                $successSql = "INSERT INTO `dkh_wx_message_member_mutil` (`send_id`,`user_id`,`send_result`,`created`,`modified`) VALUES " . substr($successValues, 0, -1) . ‘;‘;
                //插入发送成功数据
                $dkhWxMessageMemberMutilModel->baseExecuteSql($successSql);
            }

 

            //消费减余额
            $balance = $balanceData[‘balance‘] - $data[‘balance‘];
            $map = [‘and‘];
            $map[] = [‘=‘, ‘member_id‘, $orderData[‘member_id‘]];
            $map[] = [‘>=‘, ‘balance‘, $data[‘balance‘]];
            $balanceOk = $dkhMemberExtendModel->baseUpdateData([‘balance‘ => $balance], $map);

 

            //首充 ,可参加充值赠送活动
            $condition = [‘and‘];
            $condition[] = [‘=‘, ‘dkh_recharge_activity.shop_id‘, $data[‘shop_id‘]];
            $condition[] = [‘=‘, ‘dkh_recharge_activity.is_del‘, 0];
            $condition[] = [‘=‘, ‘dkh_recharge_activity.status‘, 1];
            $condition[] = [‘<=‘, ‘dkh_recharge_activity.start_time‘, $now];
            $condition[] = [‘>=‘, ‘dkh_recharge_activity.end_time‘, $now];
            $dkhRechargeActivity = new DkhRechargeActivity();
            $rechargeActivityData = $dkhRechargeActivity->baseGetOneRelation($condition, [‘dkhRechargeActivityRelation‘], ‘dkh_recharge_activity.id DESC‘);

 

 

 

以上是关于YII2.0 数据库增删改查的主要内容,如果未能解决你的问题,请参考以下文章

Yii2.0高级框架数据库增删改查的一些操作(转)

Yii2.0数据库操作增删改查详解

Yii2.0实现框架增删改查

yii2.0增删改查

yii2.0增删改查实例讲解

Express实战 - 应用案例- realworld-API - 路由设计 - mongoose - 数据验证 - 密码加密 - 登录接口 - 身份认证 - token - 增删改查API(代码片段