yii2.0總結筆記2:資料庫操作
阿新 • • 發佈:2019-02-13
<?php User::find()->one();//返回單行資料
User::find()->all();//返回多行資料
User::find()->count();//統計行數
User::find()->average();//統計平均數
User::find()->max();
User::find()->scalar();
User::find()->column();
User::find()->exists();
User::find()->batch(10);
User::find()->each();
User::find()->findByPk(1);
User::find()->findAllBySql('select * from user');
$data = (new Query)
->select('*')//查詢什麼欄位
->from('user')//查詢什麼表
->join('LEFT JOIN','orders','user.id = order.user_id')//外連線
->where(['status'=>1,'user_id'=>1])//條件
->offset(5)//跳過幾條
->limit(10)//查詢幾條
->all()
直接查詢
$sql = 'select user_id,name,account from user where user_id>10';
$rows = Yii::$app->db->createCommand($sql)->query();//
$rows = Yii::$app->db->createCommand($sql)->queryAll();
$row = Yii::$app->db->createCommand($sql)->queryOne();
關聯查詢
/**
*客戶表,訂單表,國家表
*user order country
*/
class UserModel extends yii\db\ActiveRecord{
//客戶與訂單的關係是:一對多
public function getOrder(){
return $this->hasMany(OrderModel::className(),['user_id'=>'id']);
}
//客戶與國家的關係:一對一
public function getCountry(){
return $this->hasOne(CountryModel::className(),['id'=>'country_id])
}
}
//查詢客戶他們訂單與國家的所有資訊
UserModel::find()->with('order','country')->all()
//查詢客戶與他們的訂單和訂單地址(注order與address都是關聯關係) UserModel::find()->with('order.address')->all();
增加
$user = new User;
$user->username = $username;
$user->password = $password;
$user->save();
批量增加
Yii::$app->db->createCommand->batchInsert('user',[
['test1',30],
['test2',20],
['test3',15]
])->execute();
修改
$user = User::find()->where(['name'=>'test'])->one();
$user->age = 40;
$user->save();
直接修改:修改test使用者的age為40
$result = User::model->updateAll(['age'=>40],['name'=>'test']);
使用createCommand修改
Yii::$app->db->createCommand()->update('user',['age'=>40],'name=test')->execute();
刪除
使用model::delete()刪除
$user = User::find()->where()->one();
$user ->delete();
直接刪除:年齡為30的所有使用者
$result = User::deleteAll(['age'=>'30']);
根據主鍵刪除:
$result = USer::deleteByPk(1);
Yii::$app->db->createCommand()->delete('user','age'=>30)->execute();