YII2增刪改查

1、ActiveRecord 類型的增刪改查
以\app\models\Article 模型爲準 , 來操作以下函數

1) 查詢數據
①findAll 查詢多條數據
\app\models\Article::findAll([‘status’ => ‘1’]); //查詢 Article , status 爲 1 的所有數據
②根據 findOne 進行查詢 , 根式\app\models\Article::findOne(‘條件’);
\app\models\Article::findOne(1); //直接根據 id 查詢
\app\models\Article::findOne([‘status’ => ‘1’]); //根據指定條件查詢
③根據 find()進行查詢 , find 可以連接查詢
//查詢一條 id 等於 1 的數據
\app\model\Article::find()->where([‘id’ => 1])->one();
//查詢 status 等於 1 的所有數據
\app\model\Article::find()->where([‘status’ => ‘1’])->all();

\app\model\Article::find()->where(‘status=:status’ , [‘:status’ => ‘1’])->all();
//查詢 status 等於 1 的所有數據 , 根據 date 排序
\app\model\Article::find()->where([‘status’ => ‘1’])->orderBy(‘date DESC’)->all();
//查詢 status 等於 1 的數據 , 根據 date 排序 , 從第 5 條開始,讀取 3 條
\app\model\Article::find()->where([‘status’=>‘1’])->orderBy(‘date DESC’)->offset(5) ->limit(3) ->all();
④更新一條數據
$article = \app\models\Article::findOne(1);
$article -> title = ‘change title’;
//save 函數第一個參數默認爲 true , 就是更新或插入啓動驗證
//如果不想使用驗證可以用 save(false);
$article -> save();
⑤更新指定屬性 updateAll(‘更新的屬性’ , ‘條件’ )
\app\models\Article::updateAll([‘title’ => ‘change title’ ] , [‘id’ => 1]);
⑥添加一條新數據
$article = new \app\models\Article();
$article -> title = ‘new one’;
$article -> content = ‘this is new’;
$article -> save();
⑦刪除一條數據
\app\models\Article::findOne(1)->delete();
⑧刪除指定條件的數據
\app\models\Article::deleteAll([‘id’ => 2]);
2、\yii\db\Query 查詢數據
$db = new \yii\db\Query;
//查詢一條 id 等於 2 的數據
$db->select('id')->from('mrs_article')->where("id=:id " , [':id' => 2])->one();
$db->select('id')->from('mrs_article')->where([‘id’ => 1])->one();
//查詢多條
$db->select('id')->from('mrs_article')->where([‘status’ => ‘1’])->all();
//in 查詢多條
$db->select('id')->from('mrs_article')->where([‘id’ =>[1,2]])->all();
//根據時間排序 ,並且從第 5 條開始獲取 3 條
$db->select(‘id’)->from(‘mrs_article’)->orderBy(‘date DESC’)->offset(5)->limit(3)->all()
//查詢數據總個數
$db->select('id')->from('mrs_article')->count();
3、Yii::$app->db 進行增刪改查
① 查詢數據
//查詢一條數據
\Yii::$app->db->createCommand(“SELECT * FROM mrs_article”)->queryOne();
//綁定單個防注入參數
\Yii::$app->db->createCommand(“SELECT * FROM mrs_article where id=:id”)
->bindValue(“:id” , 2)->queryOne();
//綁定多個防注入參數
\Yii::$app->db->createCommand(“SELECT * FROM mrs_article where id=:id AND
status=:status”) ->bindValues([‘:id’ => 1 , ‘:status’ => ‘1’])->queryOne();
//查詢多條數據
\Yii::$app->db->createCommand(“SELECT * FROM mrs_article”)->queryAll();
//查詢指定數據的字段的數據
$db =\Yii::$app->db;
$db->createCommand(“SELECT COUNT(*) FROM mrs_article”)->queryScalar();
② 更新數據
$db = \Yii::$app->db->createCommand();
$db->update(‘mrs_article’ , [‘status’=>0] , “id=:id” , [‘:id’ => 1])->execute();
③插入數據
$db = \Yii::$app->db->createCommand();
$db->insert(‘mrs_article’ , [‘title’=>’new Record’] )->execute();
④刪除數據
$db = \Yii::$app->db->createCommand();
$db->delete(‘mrs_article’ , “id=:id” , [‘:id’ => 1] )->execute();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章