[moka同窗筆記轉載]Yii2.0數據庫操做增刪改查詳解 [ 2.0 版本 ]

1.簡單查詢:php

 
one(): 根據查詢結果返回查詢的第一條記錄。  
  
all(): 根據查詢結果返回全部記錄。  
  
count(): 返回記錄的數量。  
  
sum(): 返回指定列的總數。  
  
average(): 返回指定列的平均值。  
  
min(): 返回指定列的最小值。  
  
max(): 返回指定列的最大值。  
  
scalar(): 返回查詢結果的第一行中的第一列的值。  
  
column(): 返回查詢結果中的第一列的值。  
  
exists(): 返回一個值,該值指示查詢結果是否有數據。  
  
where(): 添加查詢條件  
  
with(): 該查詢應執行的關係列表。  
  
indexBy(): 根據索引的列的名稱查詢結果。  
  
asArray(): 以數組的形式返回每條記錄。  

 

 應用實例:sql

Customer::find()->one();    此方法返回一條數據;

Customer::find()->all();    此方法返回全部數據;

Customer::find()->count();    此方法返回記錄的數量;

Customer::find()->average();    此方法返回指定列的平均值;

Customer::find()->min();    此方法返回指定列的最小值 ;

Customer::find()->max();    此方法返回指定列的最大值 ;

Customer::find()->scalar();    此方法返回值的第一行第一列的查詢結果;

Customer::find()->column();    此方法返回查詢結果中的第一列的值;

Customer::find()->exists();    此方法返回一個值指示是否包含查詢結果的數據行;
Customer::find()->asArray()->one();    以數組形式返回一條數據;

Customer::find()->asArray()->all();    以數組形式返回全部數據;
Customer::find()->where($condition)->asArray()->one();    根據條件以數組形式返回一條數據;

Customer::find()->where($condition)->asArray()->all();    根據條件以數組形式返回全部數據;
Customer::find()->where($condition)->asArray()->orderBy('id DESC')->all();    根據條件以數組形式返回全部數據,並根據ID倒序;

 


2.關聯查詢:數組

 
ActiveRecord::hasOne():返回對應關係的單條記錄  
ActiveRecord::hasMany():返回對應關係的多條記錄  

 

應用實例:app

//客戶表Model:CustomerModel   
//訂單表Model:OrdersModel  
//國家表Model:CountrysModel  
//首先要創建表與表之間的關係   
//在CustomerModel中添加與訂單的關係  
        
Class CustomerModel extends yiidbActiveRecord  
{  
    ...  
      
    public function getOrders()  
    {  
        //客戶和訂單是一對多的關係因此用hasMany  
        //此處OrdersModel在CustomerModel頂部別忘了加對應的命名空間  
        //id對應的是OrdersModel的id字段,order_id對應CustomerModel的order_id字段  
        return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);  
    }  
       
    public function getCountry()  
    {  
        //客戶和國家是一對一的關係因此用hasOne  
        return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);  
    }  
    ....  
}  
        
// 查詢客戶與他們的訂單和國家  
CustomerModel::find()->with('orders', 'country')->all();  
  
// 查詢客戶與他們的訂單和訂單的發貨地址  
CustomerModel::find()->with('orders.address')->all();  
  
// 查詢客戶與他們的國家和狀態爲1的訂單  
CustomerModel::find()->with([  
    'orders' => function ($query) {  
        $query->andWhere('status = 1');  
        },  
        'country',  
])->all();  

 

注:with中的orders對應getOrdersyii

常見問題:post

1.在查詢時加了->select();以下,要加上order_id,即關聯的字段(好比:order_id)好比要在select中,不然會報錯:undefined index order_idui

  1. // 查詢客戶與他們的訂單和國家  
    CustomerModel::find()->select('order_id')->with('orders', 'country')->all();  

     


findOne()和findAll():
// 查詢key值爲10的客戶  
$customer = Customer::findOne(10);  
$customer = Customer::find()->where(['id' => 10])->one();  
// 查詢年齡爲30,狀態值爲1的客戶  
$customer = Customer::findOne(['age' => 30, 'status' => 1]);  
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();  
// 查詢key值爲10的全部客戶  
$customers = Customer::findAll(10);  
$customers = Customer::find()->where(['id' => 10])->all();  
// 查詢key值爲10,11,12的客戶  
$customers = Customer::findAll([10, 11, 12]);  
$customers = Customer::find()->where(['id' => [10, 11, 12]])->all();  
// 查詢年齡爲30,狀態值爲1的全部客戶  
$customers = Customer::findAll(['age' => 30, 'status' => 1]);  
$customers = Customer::find()->where(['age' => 30, 'status' => 1])->all();  

 


where()條件:this

$customers = Customer::find()->where($cond)->all(); 

$cond寫法舉例:spa

 
// SQL: (type = 1) AND (status = 2).  
$cond = ['type' => 1, 'status' => 2]   
  
// SQL:(id IN (1, 2, 3)) AND (status = 2)  
$cond = ['id' => [1, 2, 3], 'status' => 2]   
  
//SQL:status IS NULL  
$cond = ['status' => null]  

 

[[and]]:將不一樣的條件組合在一塊兒,用法舉例:.net

 
//SQL:`id=1 AND id=2`  
$cond = ['and', 'id=1', 'id=2']  
  
//SQL:`type=1 AND (id=1 OR id=2)`  
$cond = ['and', 'type=1', ['or', 'id=1', 'id=2']]  

 

[[or]]:

 
//SQL:`(type IN (7, 8, 9) OR (id IN (1, 2, 3)))`  
$cond = ['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]] 

 

[[not]]: 

//SQL:`NOT (attribute IS NULL)`  
$cond = ['not', ['attribute' => null]]  

 

[[between]]: not between 用法相同

 

//SQL:`id BETWEEN 1 AND 10`  
$cond = ['between', 'id', 1, 10]  

 

[[in]]: not in 用法相似

//SQL:`id IN (1, 2, 3)`  
$cond = ['in', 'id', [1, 2, 3]]  
  
//IN條件也適用於多字段  
$cond = ['in', ['id', 'name'], [['id' => 1, 'name' => 'foo'], ['id' => 2, 'name' => 'bar']]]  
  
//也適用於內嵌sql語句  
$cond = ['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' => 1])]  

 

[[like]]: 

//SQL:`name LIKE '%tester%'`  
$cond = ['like', 'name', 'tester']  
  
//SQL:`name LIKE '%test%' AND name LIKE '%sample%'`  
$cond = ['like', 'name', ['test', 'sample']]  
  
//SQL:`name LIKE '%tester'`  
$cond = ['like', 'name', '%tester', false]  

 

[[exists]]: not exists用法相似

 
//SQL:EXISTS (SELECT "id" FROM "users" WHERE "active"=1)  
$cond = ['exists', (new Query())->select('id')->from('users')->where(['active' => 1])]  

 

此外,您能夠指定任意運算符以下

 
//SQL:`id >= 10`  
$cond = ['>=', 'id', 10]  
  
//SQL:`id != 10`  
$cond = ['!=', 'id', 10]  

 


經常使用查詢:

 
// WHERE admin_id >= 10 LIMIT 0,10  
 User::find()->select('*')->where(['>=', 'admin_id', 10])->offset(0)->limit(10)->all()  
// SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`     
 $subQuery = (new Query())->select('COUNT(*)')->from('user');      
 $query = (new Query())->select(['id', 'count' => $subQuery])->from('post');  
  // SELECT DISTINCT `user_id` ...   
 User::find()->select('user_id')->distinct();  

 

更新:

 
//update();  
//runValidation boolen 是否經過validate()校驗字段 默認爲true   
//attributeNames array 須要更新的字段   
$model->update($runValidation , $attributeNames);    
  
//updateAll();  
//update customer set status = 1 where status = 2  
Customer::updateAll(['status' => 1], 'status = 2');   
  
//update customer set status = 1 where status = 2 and uid = 1;  
Customer::updateAll(['status' => 1], ['status'=> '2','uid'=>'1']);  

 

刪除:

 
$model = Customer::findOne($id);  
$model->delete();  
  
$model->deleteAll(['id'=>1]);  
 

 

批量插入:

 
Yii::$app->db->createCommand()->batchInsert(UserModel::tableName(), ['user_id','username'], [  
    ['1','test1'],  
    ['2','test2'],  
    ['3','test3'],     
])->execute();  

 

查看執行sql

 
//UserModel   
$query = UserModel::find()->where(['status'=>1]);   
echo $query->createCommand()->getRawSql();  

 

 
相關文章
相關標籤/搜索