Yii2.0 增刪改查
阿新 • • 發佈:2019-02-06
- //關閉csrf
- public$enableCsrfValidation = false;
- 1.sql語句
- //查詢
- $db=\Yii::$app->db ->createCommand("select * from 表名") ->queryAll();
- //修改
- $db=\Yii::$app->db ->createCommand()->update('表名',['欄位名'=>要修改的值],'條件') ->execute();
- // 刪除
- $db=\Yii::$app->db ->createCommand() ->delete('表名'
- //新增
- $db=\Yii::$app->db ->createCommand() ->insert('表名',['欄位名'=>要新增的值],'條件') ->execute();
//應用例項
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倒序; 3.關聯查詢 ActiveRecord::hasOne():返回對應關係的單條記錄
- ActiveRecord::hasMany():返回對應關係的多條記錄
- //客戶表Model:CustomerModel
- //訂單表Model:OrdersModel
- //國家表Model:CountrysModel
- //首先要建立表與表之間的關係
- //在CustomerModel中新增與訂單的關係
- Class CustomerModel extends yiidbActiveRecord
- {
- ...
- publicfunction getOrders()
- {
- //客戶和訂單是一對多的關係所以用hasMany
- //此處OrdersModel在CustomerModel頂部別忘了加對應的名稱空間
- //id對應的是OrdersModel的id欄位,order_id對應CustomerModel的order_id欄位
- return$this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
- }
- publicfunction 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對應getOrders
常見問題:
1.在查詢時加了->select();如下,要加上order_id,即關聯的欄位(比如:order_id)比如要在select中,否則會報錯:undefined index order_id
- //查詢客戶與他們的訂單和國家
- 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()條件:
$customers = Customer::find()->where($cond)->all();
$cond寫法舉例:
- //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]]:將不同的條件組合在一起,用法舉例:
- //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
- p; 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();