欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

YII数据库查询

程序员文章站 2024-01-31 15:01:16
...

$userModel = User::Model(); $userModel-count(); $userModel-count($condition); $userModel-count($condition, $params); $userModel-countByAttributes($attributes); $userModel-countByAttributes($attributes, $condition); $userModel-countByAttrib

        $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."
"; 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]."
"; }

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

讲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);
        }