一、基本查詢
User::find()->all(); //返回所有數據;
User::findOne($id); //返回 主鍵 id=1 的一條數據(舉個例子);
User::find()->where(['name' => '小伙兒'])->one(); //返回 ['name' => '小伙兒'] 的一條數據;
User::find()->where(['name' => '小伙兒'])->all(); //返回 ['name' => '小伙兒'] 的所有數據;
User::find()->orderBy('id DESC')->all(); //是排序查詢;
User::findBySql('SELECT * FROM user')->all(); //是用 sql 語句查詢 user 表里面的所有數據;
User::findBySql('SELECT * FROM user')->one(); //是用 sql 語句查詢 user 表里面的一條數據;
User::find()->andWhere(['sex' => '男', 'age' => '24'])->count('id'); //統計符合條件的總條數;
User::find()->andFilterWhere(['like', 'name', '小伙兒']); //是用 like 查詢 name 等於 小伙兒的 數據
User::find()->one(); //返回一條數據;
User::find()->all(); //返回所有數據;
User::find()->count(); //返回記錄的數量;
User::find()->average(); //返回指定列的平均值;
User::find()->min(); //返回指定列的最小值 ;
User::find()->max(); //返回指定列的最大值 ;
User::find()->scalar(); //返回值的第一行第一列的查詢結果;
User::find()->column(); //返回查詢結果中的第一列的值;
User::find()->exists(); //返回一個值指示是否包含查詢結果的數據行;
User::find()->batch(10); //每次取 10 條數據
User::find()->each(10); //每次取 10 條數據, 迭代查詢
原文鏈接:http://www.yiichina.com/tutorial/95
二、and 和 or 復合句
->andWhere['customer_id'=>$customerId] ->andWhere(['or' ['customer_name' => $customername], ['LIKE', 'phone' , $phone], ]) // WHERE customer_id=1 AND (customer_name='張三' OR phone LIKE 13123456789)
->andWhere['customer_id'=>$customerId] ->orWhere(['and' ['customer_name' => $customername], ['LIKE', 'phone' , $phone], ]) // WHERE customer_id=1 OR (customer_name='張三' AND phone LIKE 13123456789) //2、如果需要些 and和or 的復合句,則:
->andWhere['customer_id'=>$customerId] ->andWhere(['or' ['status' => $status], ['and', ['customer_name' => $customername], ['LIKE', 'phone' , $phone], ], ]) // WHERE customer_id=1 AND ('status'=>1 OR (customer_name='張三' AND phone LIKE 13123456789)) //3、如果需要一些特殊的形式,則使用 new \yii\db\Expression();
->andWhere['customer_id'=>$customerId] ->andWhere(['or' ['status' => $status], ['and', ['customer_name' => $customername], ['IS NOT', phone' , new \yii\db\Expression('NULL')], ], ]) // WHERE customer_id=1 AND ('status'=>1 OR (customer_name='張三' AND phone IS NOT NULL))
三、modelName::updateAll($attributes, $condition = '', $params = [])
第一個參數是要更新的值,第二個是條件,如果第二個條件中用了占位符,就必須 要有第三個條件。 平時我們查詢 的時候用 andWhere()
可以連接很多參數,那么 updateAll()
的時候,如果有多個參數怎么辦?
User::updateAll(['status' => 1],['status' => 0,'flag' => 1]);
果參數都是固定值,這樣的寫法當然 OK,如果有范圍值就只能這樣寫了,比如 flag != 1
怎么辦?
User::updateAll(['status' => 1],['and', ['status' => 0],['<>', 'flag', 1]]);
原文鏈接:https://www.yiichina.com/tutorial/1842
`