首页 > 代码库 > YII 数据库查询

YII 数据库查询

        $userModel = User::Model();
        $userModel->count();
        $userModel->count($condition);
        $userModel->count($condition, $params);
        $userModel->countByAttributes($attributes);
        $userModel->countByAttributes($attributes, $condition);
        $userModel->countByAttributes($attributes, $condition, $params);
        $userModel->countBySql($sql);
        $userModel->countBySql($sql, $params);
        
      //  $userModel = User::Model();
        $userModel->find();
        $userModel->find($condition);
        $userModel->find($condition, $params);
        
        $userModel->findByPk($pk);
        $userModel->findByPk($pk, $condition);
        $userModel->findByPk($pk, $condition, $params);
        $userModel->findByAttributes($attributes);
        $userModel->findByAttributes($attributes, $userModel);
        $userModel->findByAttributes($attributes, $userModel, $params);
        
        $userModel->findBySql($sql);
        $userModel->findBySql($sql, $params);

        //返回值为对象数组,若为空则返回NULL。为一条记录
        $findResult = $userModel->find('islock = :islock and phone_status=:phone_status',array(':islock' => 1,':phone_status'=>1));
        echo $findResult -> phone_status."<br />";
        var_dump($findResult->attributes);
        if($userModel->find('user_id=260')){
            echo 'find';
        }else{
            echo 'no find';
        }


參数解释:上面均返回一条记录 假设要返回多条数据findALL类似的

$condition 是一般sql里面where子句,一个字符窜

$params 是一个数组,为占位符赋值

查询出来全部数据:

        $userinfo= $userModel->findAllByAttributes(array('islock'=>1,'phone_status' => 0));
        foreach($userinfo as $k => $v){
            echo $v->user_id."  ".  $userinfo[$k][user_id]."<br />";
        }

可见。结果是一个二维数组。

讲CDbcriteria和Model对象进行结合

        $criteria = new CDbCriteria; 
        if($condition) $criteria->condition = $condition;
        $criteria->offset = $offset;
        if($order) $criteria->order = $order;
        if($limit!="ALL") $criteria->limit = $limit;
        if(!empty($more_criteria)){
            $criteria->mergeWith($more_criteria);
        }
        $Model = new $modelName;

        if(!empty($with_array)){
            $result = $Model->with($with_array)->findAllByAttributes($attributes,$criteria);
        }else{
            $result = $Model->findAllByAttributes($attributes,$criteria);
        }




YII 数据库查询