yii2.0 curd操做數據寫法

1、執行原生sql查詢,建立yii\db\Command         insert(),update(),delete()直接構建,相應的sql語句sql

查:
app

1.查詢一條 \Yii::$app->db->createCommand('SELECT * FROM test')->queryOne(); 2.查詢多條 \Yii::$app->db->createCommand('SELECT * FROM test')->queryAll(); 3.綁定單個防SQL注入參數 \Yii::$app->db->createCommand('SELECT * FROM test WHERE id=:id')->bindValue(':id',5)->queryOne(); 4.綁定多個防SQL注入參數 \Yii::$app->db->createCommand('SELECT * FROM test WHERE id=:id AND name=:name')->bindValues([':id'=>3,':name'=>'Tom'])->queryOne(); 5.統計查詢 \Yii::$app->db->createCommand('SELECT COUNT("id") FROM test')->queryScalar();

 增:yii

1.插入數據 \Yii::$app->db->createCommand()->insert('test',['name'=>'James','age'=>'22'])->execute(); 2.一次插入多行 \Yii::$app->db->createCommand()->batchInsert('test',['name','age'],[ ['Hong','33'], ['Wei','44'] ])->execute();

 改:spa

修改數據 \Yii::$app->db->createCommand()->update('test',['name'=>'Li'],'id=:id and class=:class',[':id'=>1,':class'=>'E'])->execute();

刪:code

刪除數據 \Yii::$app->db->createCommand()->delete('test','id>:id',[':id'=>6])->execute();

 

2、查詢構建器,建立yii\db\Queryblog

查:it

1.查詢一條 $row = (new \yii\db\Query()) ->select('*') ->from('test') ->where('id=:id', [':id'=>6]) ->one(); 2.查詢多條 $rows = (new \yii\db\Query()) ->select('id,name') ->from('test') ->where(['>','id', 2]) ->andWhere('class=:class', [':class'=>'A']) ->all(); 3.統計查詢 $count = (new \yii\db\Query()) ->select('count(id)') ->from('test') ->where('class=:class', [':class'=>'B']) ->count(); 4.關聯查詢 $join = (new \yii\db\Query()) ->from('student s') ->select('s.*,t.id t_id,t.name t_name') ->leftJoin('teacher t','s.class = t.class') ->where('t.id=:t_id', [':t_id' => '2']) ->offset(3) ->limit(2) ->all();

 

3、建模ORM class

test

插入數據 $add = new Test(); $add->name = 'Xing'; $add->class = 'B'; $add->save();

查:date

1.查詢一條 $row = Test::find()->where('id=:id',[':id'=>5])->asArray()->one(); 2.查詢多條 $rows = Test::find()->where('id>:id and class=:class',[':id'=>12,':class'=>'C'])->asArray()->all(); 3.統計查詢 $count = Test::find()->count();

改:

1.save()進行修改 $update = Test::find()->where('id=:id',[':id'=>6])->one(); $update->score = 100;//修改屬性值
$update->save(); 2.方法updateAll() $updateAll = Test::updateAll(['name'=>'Ping'],'id=:id',[':id'=>10]);

刪:

1.先查後刪 $del = Test::find()->where('id=:id',[':id'=>6])->one(); $del->delete(); 2.直接刪除 Test::deleteAll('id>:id', [':id' => 29]);
相關文章
相關標籤/搜索