溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Yii2.0 數(shù)據(jù)庫增刪改查的操作示例

發(fā)布時間:2021-01-06 12:28:16 來源:億速云 閱讀:128 作者:小新 欄目:編程語言

小編給大家分享一下Yii2.0 數(shù)據(jù)庫增刪改查的操作示例,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

1.簡單查詢:

one(): 根據(jù)查詢結(jié)果返回查詢的第一條記錄。
all(): 根據(jù)查詢結(jié)果返回所有記錄。
count(): 返回記錄的數(shù)量。
sum(): 返回指定列的總數(shù)。
average(): 返回指定列的平均值。
min(): 返回指定列的最小值。
max(): 返回指定列的最大值。
scalar(): 返回查詢結(jié)果的第一行中的第一列的值。
column(): 返回查詢結(jié)果中的第一列的值。
exists(): 返回一個值,該值指示查詢結(jié)果是否有數(shù)據(jù)。
where(): 添加查詢條件
with(): 該查詢應(yīng)執(zhí)行的關(guān)系列表。
indexBy(): 根據(jù)索引的列的名稱查詢結(jié)果。
asArray(): 以數(shù)組的形式返回每條記錄。

應(yīng)用實例:

Customer::find()->one();    此方法返回一條數(shù)據(jù);
Customer::find()->all();    此方法返回所有數(shù)據(jù);
Customer::find()->count();    此方法返回記錄的數(shù)量;
Customer::find()->average();    此方法返回指定列的平均值;
Customer::find()->min();    此方法返回指定列的最小值 ;
Customer::find()->max();    此方法返回指定列的最大值 ;
Customer::find()->scalar();    此方法返回值的第一行第一列的查詢結(jié)果;
Customer::find()->column();    此方法返回查詢結(jié)果中的第一列的值;
Customer::find()->exists();    此方法返回一個值指示是否包含查詢結(jié)果的數(shù)據(jù)行;
Customer::find()->asArray()->one();    以數(shù)組形式返回一條數(shù)據(jù);
Customer::find()->asArray()->all();    以數(shù)組形式返回所有數(shù)據(jù);
Customer::find()->where($condition)->asArray()->one();    根據(jù)條件以數(shù)組形式返回一條數(shù)據(jù);
Customer::find()->where($condition)->asArray()->all();    根據(jù)條件以數(shù)組形式返回所有數(shù)據(jù);
Customer::find()->where($condition)->asArray()->orderBy('id DESC')->all();    根據(jù)條件以數(shù)組形式返回所有數(shù)據(jù),并根據(jù)ID倒序;

2.關(guān)聯(lián)查詢:

ActiveRecord::hasOne():返回對應(yīng)關(guān)系的單條記錄
ActiveRecord::hasMany():返回對應(yīng)關(guān)系的多條記錄

應(yīng)用實例:

//客戶表Model:CustomerModel 
//訂單表Model:OrdersModel
//國家表Model:CountrysModel
//首先要建立表與表之間的關(guān)系 
//在CustomerModel中添加與訂單的關(guān)系
      
Class CustomerModel extends yiidbActiveRecord
{
    ...
    
    public function getOrders()
    {
        //客戶和訂單是一對多的關(guān)系所以用hasMany
        //此處OrdersModel在CustomerModel頂部別忘了加對應(yīng)的命名空間
        //id對應(yīng)的是OrdersModel的id字段,order_id對應(yīng)CustomerModel的order_id字段
        return $this->hasMany(OrdersModel::className(), ['id'=>'order_id']);
    }
     
    public function getCountry()
    {
        //客戶和國家是一對一的關(guān)系所以用hasOne
        return $this->hasOne(CountrysModel::className(), ['id'=>'Country_id']);
    }
    ....
}
      
// 查詢客戶與他們的訂單和國家
CustomerModel::find()->with('orders', 'country')->all();

// 查詢客戶與他們的訂單和訂單的發(fā)貨地址
CustomerModel::find()->with('orders.address')->all();

// 查詢客戶與他們的國家和狀態(tài)為1的訂單
CustomerModel::find()->with([
    'orders' => function ($query) {
        $query->andWhere('status = 1');
        },
        'country',
])->all();

注:with中的orders對應(yīng)getOrders

常見問題:

在查詢時加了->select();如下,要加上order_id,即關(guān)聯(lián)的字段(比如: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,狀態(tài)值為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,狀態(tài)值為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']]]

//也適用于內(nèi)嵌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])]
此外,您可以指定任意運(yùn)算符如下

//SQL:`id >= 10`
$cond = ['>=', 'id', 10]

//SQL:`id != 10`
$cond = ['!=', 'id', 10]

常用查詢:

// WHERE admin_id >= 10 LIMIT 0,10
 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()校驗字段 默認(rèn)為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();

查看執(zhí)行sql

//UserModel 
$query = UserModel::find()->where(['status'=>1]); 
echo $query->createCommand()->getRawSql();

以上是“Yii2.0 數(shù)據(jù)庫增刪改查的操作示例”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI