Yii2 數據庫操做彙總

對象操做sql

查詢數據庫

  1 //1.簡單查詢
  2 $admin=Admin::model()->findAll($condition,$params);
  3 $admin=Admin::model()->findAll("username=:name",array(":name"=>$username));
  4  
  5 $infoArr= NewsList::model()->findAll("status = '1' ORDER BY id DESC limit 10 ");
  6  
  7 //2. findAllByPk(該方法是根據主鍵查詢一個集合,可使用多個主鍵)
  8 $admin=Admin::model()->findAllByPk($postIDs,$condition,$params);
  9 $admin=Admin::model()->findAllByPk($id,"name like :name and age=:age",array(':name'=>$name,'age'=>$age));
 10 $admin=Admin::model()->findAllByPk(array(1,2));
 11  
 12 //3.findAllByAttributes (該方法是根據條件查詢一個集合,能夠是多個條件,把條件放到數組裏面)
 13 $admin=Admin::model()->findAllByAttributes($attributes,$condition,$params);
 14 $admin=Admin::model()->findAllByAttributes(array('username'=>'admin'));
 15  
 16 //4.findAllBySql (該方法是根據SQL語句查詢一個數組)
 17 $admin=Admin::model()->findAllBySql($sql,$params);
 18 $admin=Admin::model()->findAllBySql("select * from admin where username like :name",array(':name'=>'%ad%'));
 19 User::find()->all();    此方法返回全部數據;
 20 User::findOne($id);   此方法返回 主鍵 id=1  的一條數據(舉個例子); 
 21 User::find()->where(['name' => '小夥兒'])->one();   此方法返回 ['name' => '小夥兒'] 的一條數據;
 22 User::find()->where(['name' => '小夥兒'])->all();   此方法返回 ['name' => '小夥兒'] 的全部數據;
 23 User::find()->orderBy('id DESC')->all();   此方法是排序查詢;
 24 User::findBySql('SELECT * FROM user')->all();  此方法是用 sql  語句查詢 user 表裏面的全部數據;
 25 User::findBySql('SELECT * FROM user')->one();  此方法是用 sql  語句查詢 user 表裏面的一條數據;
 26 User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id');   統計符合條件的總條數;
 27 User::find()->one();    此方法返回一條數據;
 28 User::find()->all();    此方法返回全部數據;
 29 User::find()->count();    此方法返回記錄的數量;
 30 User::find()->average();    此方法返回指定列的平均值;
 31 User::find()->min();    此方法返回指定列的最小值 ;
 32 User::find()->max();    此方法返回指定列的最大值 ;
 33 User::find()->scalar();    此方法返回值的第一行第一列的查詢結果;
 34 User::find()->column();    此方法返回查詢結果中的第一列的值;
 35 User::find()->exists();    此方法返回一個值指示是否包含查詢結果的數據行;
 36 User::find()->batch(10);  每次取 10 條數據 
 37 User::find()->each(10);  每次取 10 條數據, 迭代查詢
 38 2、查詢對象的方法
 39 //根據主鍵查詢出一個對象,如:findByPk(1);
 40 $admin=Admin::model()->findByPk($postID,$condition,$params);
 41 $admin=Admin::model()->findByPk(1);
 42  
 43 //根據一個條件查詢出一組數據,多是多個,可是他只返回第一行數據
 44 $row=Admin::model()->find($condition,$params);
 45 $row=Admin::model()->find('username=:name',array(':name'=>'admin'));
 46  
 47 //該方法是根據條件查詢一組數據,能夠是多個條件,把條件放到數組裏面,查詢的也是第一條數據
 48 $admin=Admin::model()->findByAttributes($attributes,$condition,$params);
 49 $admin=Admin::model()->findByAttributes(array('username'=>'admin'));
 50  
 51 //該方法是根據SQL語句查詢一組數據,他查詢的也是第一條數據
 52 $admin=Admin::model()->findBySql($sql,$params);
 53 $admin=Admin::model()->findBySql("select * from admin where username=:name",array(':name'=>'admin'));
 54  
 55 //拼一個得到SQL的方法,在根據find查詢出一個對象 
 56 $criteria=newCDbCriteria; 
 57 $criteria->select='username';// only select the 'title' column 
 58 $criteria->condition='username=:username';    //請注意,這是一個查詢的條件,且只有一個查詢條件.多條件用addCondition
 59 $criteria->params=array(":username=>'admin'");
 60 $criteria->order ="id DESC";
 61 $criteria->limit ="3";
 62 $post=Post::model()->find($criteria);// $params isnot needed 
 63  
 64 //多條件查詢的語句
 65 $criteria= new CDbCriteria;     
 66 $criteria->addCondition("id=1");//查詢條件,即where id = 1 
 67 $criteria->addInCondition('id',array(1,2,3,4,5));//表明where id IN (1,2,3,4,5,); 
 68 $criteria->addNotInCondition('id',array(1,2,3,4,5));//與上面正好相法,是NOT IN 
 69 $criteria->addCondition('id=1','OR');//這是OR條件,多個條件的時候,該條件是OR而非AND 
 70 $criteria->addSearchCondition('name','分類');//搜索條件,其實表明了。。where name like '%分類%' 
 71 $criteria->addBetweenCondition('id', 1, 4);//between 1 and 4
 72 $criteria->compare('id', 1);   //這個方法比較特殊,他會根據你的參數自動處理成addCondition或者addInCondition.
 73 $criteria->compare('id',array(1,2,3));   //即若是第二個參數是數組就會調用addInCondition 
 74  
 75  
 76 $criteria->select ='id,parentid,name';//表明了要查詢的字段,默認select='*'; 
 77 $criteria->join ='xxx'; //鏈接表 
 78 $criteria->with ='xxx'; //調用relations  
 79 $criteria->limit = 10;   //取1條數據,若是小於0,則不做處理 
 80 $criteria->offset = 1;  //兩條合併起來,則表示 limit 10 offset 1,或者表明了。limit 1,10 
 81 $criteria->order ='xxx DESC,XXX ASC' ;//排序條件 
 82 $criteria->group ='group 條件'; 
 83 $criteria->having ='having 條件 '; 
 84 $criteria->distinct = FALSE;//是否惟一查詢
 85 3、查詢個數,判斷查詢是否有結果
 86 //該方法是根據一個條件查詢一個集合有多少條記錄,返回一個int型數字
 87 $n=Post::model()->count($condition,$params);
 88 $n=Post::model()->count("username=:name",array(":name"=>$username));
 89  
 90 //該方法是根據SQL語句查詢一個集合有多少條記錄,返回一個int型數字
 91 $n=Post::model()->countBySql($sql,$params);
 92 $n=Post::model()->countBySql("select * from admin where username=:name",array(':name'=>'admin'));
 93  
 94 //該方法是根據一個條件查詢查詢獲得的數組有沒有數據,若是有數據返回一個true,不然沒有找到
 95 $exists=Post::model()->exists($condition,$params);
 96 $exists=Post::model()->exists("name=:name",array(":name"=>$username));
 97 4、新增
 98 $admin= new Admin;       
 99 $admin->username =$username;
100 $admin->password =$password;
101 if($admin->save() > 0){echo "添加成功"; }else{echo "添加失敗"; }
102 5、修改
103 Post::model()->updateAll($attributes,$condition,$params);
104 $count=Admin::model()->updateAll(array('username'=>'11111','password'=>'11111'),'password=:pass',array(':pass'=>'1111a1'));
105 if($count> 0){ echo "修改爲功"; }else{echo "修改失敗"; }
106  
107 $rt= PostList::model()->updateAll(array('status'=>'1'),'staff_id=:staff AND host_id=:host',array(':staff'=>$staff_id,':host'=>$host_id));
108  
109 //$pk主鍵,能夠是一個也能夠是一個集合,$attributes是要修改的字段的集合,$condition條件,$params傳入的值
110 Post::model()->updateByPk($pk,$attributes,$condition,$params);
111 $count=Admin::model()->updateByPk(1,array('username'=>'admin','password'=>'admin'));
112 $count=Admin::model()->updateByPk(array(1,2),array('username'=>'admin','password'=>'admin'),'username=:name',array(':name'=>'admin'));
113 if($count>0){echo "修改爲功"; }else{echo "修改失敗"; }
114  
115 Post::model()->updateCounters($counters,$condition,$params);
116 $count=Admin::model()->updateCounters(array('status'=>1),'username=:name',array(':name'=>'admin'));
117 if($count> 0){ echo "修改爲功"; }else{echo "修改失敗"; }
118 //array('status'=>1)表明數據庫中的admin表根據條件username='admin',查詢出的全部結果status字段都自加1
119 6、刪除
120 //deleteAll
121 Post::model()->deleteAll($condition,$params);
122 $count= Admin::model()->deleteAll('username=:name and password=:pass',array(':name'=>'admin',':pass'=>'admin'));
123 $count= Admin::model()->deleteAll('id in("1,2,3")');//刪除id爲這些的數據
124 if($count>0){echo"刪除成功"; }else{echo "刪除失敗"; }
125  
126 //deleteByPk
127 Post::model()->deleteByPk($pk,$condition,$params);
128 $count= Admin::model()->deleteByPk(1);
129 $count=Admin::model()->deleteByPk(array(1,2),'username=:name',array(':name'=>'admin'));
130 if($count>0){echo "刪除成功"; }else{echo "刪除失敗"; }

直接數據庫操做數組

查詢app

 1 //createCommand(執行原生的SQL語句)  
 2     $sql= "SELECT u.account,i.* FROM sys_user as u left join user_info as i on u.id=i.user_id";  
 3     $rows=Yii::$app->db->createCommand($sql)->query();  
 4     foreach($rows as $k => $v){  
 5         echo$v['add_time'];  
 6     }  
 7       
 8     查詢返回多行:  
 9       
10     $command = $connection->createCommand('SELECT * FROM post');  
11     $posts = $command->queryAll();  
12     返回單行:  
13       
14     $command = $connection->createCommand('SELECT * FROM post WHERE id=1');  
15     $post = $command->queryOne();  
16     查詢多行單值:  
17       
18     $command = $connection->createCommand('SELECT title FROM post');  
19     $titles = $command->queryColumn();  
20     查詢標量值/計算值:  
21       
22     $command = $connection->createCommand('SELECT COUNT(*) FROM post');  
23     $postCount = $command->queryScalar();

更新post

1 $command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1'); 2 $command->execute(); 

插入更新刪除this

 1 // INSERT  
 2 $connection->createCommand()->insert('user', [  
 3     'name' => 'Sam',  
 4     'age' => 30,  
 5 ])->execute();  
 6   
 7 // INSERT 一次插入多行  
 8 $connection->createCommand()->batchInsert('user', ['name', 'age'], [  
 9     ['Tom', 30],  
10     ['Jane', 20],  
11     ['Linda', 25],  
12 ])->execute();  
13   
14 // UPDATE  
15 $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();  
16   
17 // DELETE  
18 $connection->createCommand()->delete('user', 'status = 0')->execute();

事務spa

 1 //事務的基本結構(多表更新插入操做請使用事務處理)  
 2 $dbTrans= Yii::app()->db->beginTransaction();  
 3 try{  
 4     $post= new Post;  
 5     $post->'title'= 'Hello dodobook!!!';  
 6     if(!$post->save())throw newException("Error Processing Request", 1);  
 7     $dbTrans->commit();  
 8 //  $this->_end(0,'添加成功!!!');  
 9 }catch(Exception$e){  
10     $dbTrans->rollback();  
11 //  $this->_end($e->getCode(),$e->getMessage());
相關文章
相關標籤/搜索