Yii 框架里数据库操作详解-[增加、查询、更新、删除的方法 'AR模式']

时间:2024-01-05 14:07:38

public function getMinLimit () {
        $sql = "...";
        $result = yii::app()->db->createCommand($sql);
        $query = $result->queryAll();
 
        return array (
                $query [0] ['max'], 
        );
    }

$connection=Yii::app()->db; 
$sql="SELECT u.account,i.* FROM sys_user as u left join user_info as i on u.id=i.user_id";
$rows=$connection->createCommand ($sql)->query();
foreach ($rows as $k => $v ){
    echo $v['add_time'];
}

======================================== 事务

$db = Yii::app()->db;
$dbTrans = $db->beginTransaction();

$dbTrans->commit();
$dbTrans->rollback();

======================================== 

分页

一般写法:
$criteria = new CDbCriteria;
$count = DnOnline::model()->count($criteria);
$pages = new CPagination($count);               
$pages->pageSize = 5;
$pages->applylimit($criteria);
$model = DnOnline::model()->findAll($criteria);

记得控制器里有个函数paginate($itemCount,$pageSize=null,$pageVar=null)
CDB写法:

$criteria = new CDbCriteria;
$sql = "SELECT * FROM USER";
$model= Yii::app()->db->createCommand($sql)->queryAll();
$pages = new CPagination(count($model));               
$pages->pageSize = 4;
$pages->applylimit($criteria);
$model=Yii::app()->db->createCommand($sql." LIMIT :offset,:limit");
$model->bindValue(':offset', $pages->currentPage*$pages->pageSize);
$model->bindValue(':limit', $pages->pageSize);
$model=$model->queryAll();

或者:

$criteria = new CDbCriteria;
      $connection=Yii::app()->db; 
      $sql="SELECT u.account,i.* FROM sys_user as u left join user_info as i on u.id=i.user_id ";
      $model= Yii::app()->db->createCommand($sql)->queryAll();
      $pages = new CPagination(count($model));               
      $pages->pageSize = 4;
      $pages->applylimit($criteria);

$model=Yii::app()->db->createCommand($sql." LIMIT :offset,:limit");
      $model->bindValue(':offset', $pages->currentPage*$pages->pageSize);
      $model->bindValue(':limit', $pages->pageSize);
      $model=$model->queryAll();

========================================

一、查询数据集合 

1、$admin=Admin::model()->findAll ($condition,$params);
该方法是根据一个条件查询一个集合,如:  
findAll("username=:name",array(":name"=>$username));

2、$admin=Admin::model()->findAllByPk($postIDs,$condition,$params); 
findAllByPk($id,"name like ':name' and age=:age",array(':name'=>$name,'age'=>$age));    
该方法是根据主键查询一个集合,可以使用多个主键,如:  
findAllByPk(array(1,2));

3、$admin=Admin::model()->findAllByAttributes($attributes,$condition,$params); 
该方法是根据条件查询一个集合,可以是多个条件,把条件放到数组里面,如:  
findAllByAttributes(array('username'=>'admin'));

4、$admin=Admin::model()->findAllBySql($sql,$params); 
该方法是根据SQL语句查询一个数组,如: 
findAllBySql("select *from admin whereusername=:name",array(':name'=>'admin'));

========================================

二、查询对像 的方法  

1、$admin=Admin::model()->findByPk ($postID,$condition,$params); 
 根据主键查询出一个对象,如:findByPk(1);

2、$row=Admin::model()->find ($condition,$params); 
 根据一个条件查询出一组数据,可能是多个,但是他只返回第一行数据,如: 
find('username=:name',array(':name'=>'admin'));

$userinfo=Userinfo::model()->find(array('condition'=>'user_id=:user_id','params'=>array(':user_id'=>$uid)));
      print_r($userinfo->user_id);

3、$admin=Admin::model()->findByAttributes ($attributes,$condition,$params); 
 该方法是根据条件查询一组数据,可以是多个条件,把条件放到数组里面,他查询的也是第一条数据,如: 
findByAttributes(array('username'=>'admin'));

4、$admin=Admin::model()->findBySql ($sql,$params); 
 该方法是根据SQL语句查询一组数据,他查询的也是第一条数据,如:  
findBySql("select *from admin whereusername=:name",array(':name'=>'admin'));

5、拼一个获得SQL的方法,在根据find查询出一个对象

$criteria=new CDbCriteria;  
$criteria->select='username'; // only select the 'title' column  
$criteria->condition='username=:username'; 
$criteria->params=array(':username=>'admin'); 
$post=Post::model()->find($criteria); // $params isnot needed  
 
========================================

三、查询个数,判断查询是否有结果  

1、$n=Post::model()->count ($condition,$params); 
 该方法是根据一个条件查询一个集合有多少条记录,返回一个int型数字,如  
count("username=:name",array(":name"=>$username));

2、$n=Post::model()->countBySql ($sql,$params); 
 该方法是根据SQL语句查询一个集合有多少条记录,返回一个int型数字,如 
countBySql("select *from admin whereusername=:name",array(':name'=>'admin'));

3、$exists=Post::model()->exists($condition,$params); 
 该方法是根据一个条件查询查询得到的数组有没有数据,如果有数据返回一个true,否则没有找到

$sql = "select count(*) as count  from " . $this->tableName() . " where user_id = $userId";
        $query = $result->queryAll();
        $pageSize =10;
        $count = $query [0] ['count'];
        $pageCount = ceil($count / $pageSize);
        return $pageCount;

======================================== 

四、添加的方法  
$admin=newAdmin;        
$admin->username=$username; 
$admin->password=$password; 
if($admin->save ()>0){ 
   echo "添加成功";  
}else{  
   echo "添加失败";  
}

$userLimit = new UserLimit();
$userLimit->item = 0.30000;
if($userLimit->insert (){

}

========================================

五、修改的方法 

$userLimitRet = UserLimit::model()->findByPk (array (
                                'user_id' => $userId, 
                                'category_id' => $v 
                        ));
$userLimitRet->order = $order;

if (! $userLimitRet->update ()) {
}

$userAmount=userAmount::model()->findByPk ($userId);
$userAmount->credit=Yii::app()->request->getParam('credit',10000);
$ret = $userAmount->save ();

1、Post::model()->updateAll ($attributes,$condition,$params); 
 $count =Admin::model()->updateAll(array('username'=>'11111','password'=>'11111'),'password=:pass',array(':pass'=>'1111a1')); 
if($count>0){  
   echo "修改成功";  
}else{  
   echo "修改失败";  
}

$ret = $this->updateAll (array (
                                'set' => $Set
                        ), " user_id in ( " . $userIds . " ) and category_id = " . $categoryId);

if($ret){
    return true;
}else {
    return false;
}

2、Post::model()->updateByPk ($pk,$attributes,$condition,$params); 
 $count =Admin::model()->updateByPk(1,array('username'=>'admin','password'=>'admin')); 
$count =Admin::model()->updateByPk(array(1,2),array('username'=>'admin','password'=>'admin'),'username=:name',array(':name'=>'admin'));
if($count>0){  
   echo "修改成功";  
}else{  
   echo "修改失败";  
}  
$pk代表主键,可以是一个也可以是一个集合,$attributes代表是要修改的字段的集合,$condition代表条件,$params传入的值

3、Post::model()->updateCounters ($counters,$condition,$params); 
 $count=Admin::model()->updateCounters(array('status'=>1),'username=:name',array(':name'=>'admin')); 
if($count>0){  
   echo "修改成功";  
}else{  
   echo "修改失败";  
}  
array('status'=>1)代表数据库中的admin表根据条件username='admin',查询出的所有结果status字段都自加1 
 
========================================

六、删除的方法  
1、Post::model()->deleteAll($condition,$params); 
 $count = Admin::model()->deleteAll('username=:nameandpassword=:pass',array(':name'=>'admin',':pass'=>'admin')); 
         $id=1,2,3  
         deleteAll('id in(".$id.")');删除id为这些的数据 
if($count>0){  
   echo "删除成功";  
}else{  
   echo "删除失败";  
}  
 2、Post::model()->deleteByPk($pk,$condition,$params); 
$count = Admin::model()->deleteByPk(1); 
$count =Admin::model()->deleteByPk(array(1,2),'username=:name',array(':name'=>'admin')); 
if($count>0){  
   echo "删除成功";  
}else{  
   echo "删除失败";  
}

七、like模糊查询

var $username='张三';
var $email ='qq@qq.com';
var $mobile =18888888888; $result=User::find()->where([
'status'=>1,
])->andwhere([
'or',
['like','username',$username],
['like','email',$email],
['like','mobile',$mobile],
])->all();

  

 $rows = (new \yii\db\Query())
->from('admin')
->where("status=:status and (username like :keyword or `name` like :keyword )")
->addParams([':status'=>1,':keyword'=>'%陈%'])
->all();

  

Customer::find()->andFilterWhere(['like','name','洋']);