yii2 數據庫和ActiveRecord


Yii2數據庫和 ActiveRecord 類

1、common/config/main-local.php 里面配置數據賬號和密碼。

2、ActiveRecord(活動記錄,簡稱AR類),提供了一套面向對象的接口,用以訪問數據庫中的數據

  • 一個AR類關聯一張數據表,每個AR對象對應表中的一行;
  • AR類的屬性,對應為數據庫中的列
  • 可以以面向對象的方式來操縱數據庫中的數據,這樣就不用謝 sql 語句來實現數據庫的訪問。
  • find() 方法返回一條記錄;
$model = Post::find()->where(['id'=>1])->one(); $model = Post::findOne(1);

 

  • find() 方法返回所有記錄;
$model = Post::find()->where(['status'=>1])->all(); $model = Post::findAll(['status'=>1]);
$total = User::find()->count(); // 查詢總數(count(*))

3、ActiveQueryInterface 常用方法:

  • all() 、one() --------- 執行查詢,並返回 AR 對象
  • orderBy()、andOrderBy()  ---------  排序
  • count()  ---------  返回符合查詢條件的記錄數
  • limit()  ---------  取出查詢結果的條數
  • with()  ---------  指定關聯表的字段
  • where()、andWhere()、orWhere()  ---------  查詢條件


4、where() 查詢條件的寫法:

  where 參數的寫法 sql 語句
and  ['and','id=1','id=2'] id=1 AND id=2
or ['or','id=1','id=2'] id=1 OR id=2
in ['in','id',[1,2,3]] IN(1,2,3)
between ['between','id',1,10] id BETWEEN 1 AND 10
like ['like','name',['test','sample']] name LIKE '%test%' AND name LIKE '%sample%'
比較 ['>=','id',10] id >= 10

 

5、findBySql()

  $sql = "SELECT * FROM post WHERE status = 1";

  $post = Post::findBySql($sql) -> all();

6、CRUD 操作數據

AR 提供下面這些方法來實現插入、更新、刪除等功能
a、yii\db\ActiveRecord::insert()   // 插入

$customer = new Customer(); $customer -> name = 'Carroll'; $customer -> email = 'Carroll@qq.com'
$customer -> save(); // 等同於 $customer -> insert()

b、yii\db\ActiveRecord::update()   // 更新

$customer = Customer::findOne($id); $customer -> email = '123456@qq.com'
$customer ->save(); // 等同於 $customer -> update()

c、yii\db\ActiveRecord::delete()   // 刪除

$customer = Customer::findOne($id); $customer -> delete();

d、yii\db\ActiveRecord::save()    // 可同時替代 insert() 和 update(),開發中常用 save()方法

7 、ActiveRecord 的生命周期

方法          生命周期  事件
new()    1、constructor  
2、init()    EVENT_INIT
find()  1、constructor  
2、init() EVENT_INIT
3、afterFind()  EVENT_AFTER_FIND
save() 1、beforeValidate() EVENT_BEFORE_VALIDATE
2、執行數據驗證,如通不過,則第三部后面的步驟會被略過  
3、afterValidate()  EVENT_AFTER_VALIDATE
4、beforeSave() EVENT_BEFORE_INSERT or EVENT_BEFORE_UPDATE
5、執行數據插入或修改  
6、afterSave() EVENT_AFTER_INSERT or EVENT_AFTER_UPDATE
delete() 1、beforeDelete() EVENT_BEFORE_DELETE
2、執行數據刪除  
3、afterDelete()   EVENT_AFTER_DELETE
refresh() 1、afterRefresh() EVENT_AFTER_REFRESH

可以根據 ActiveRecord 的什么周期來重寫方法,注入自己的代碼控制流程

例如重寫beforeSave(),如果這個方法執行后的結果為 false,后面的步驟就不會執行

    /** * @purpose : 將數據插入時間和更新時間插入數據庫 * @param bool $insert * @return bool */
    public function beforeSave($insert){ if(parent::beforeSave($insert)){                // 需要首先繼承父類的 beforeSave()
            if($insert){ $this->create_time = time(); $this->update_time = time(); }else{ $this->update_time = time(); } return true; }else{ return false; } }

 查詢所有的記錄:

$dataProvider->query->each()

查詢當前頁的數據:
$dataProvider->getModels()

獲取當前模型的默認值:
$model = new Test();
$model->loadDefaultValues();  // 當前模型的默認值
Yii 中的回滾操作,此處用於 當遇到 try .... cache() 的時候
$transacton = Yii::$app->dbName->beginTransaction(); try{ ...
    $model->save(); $transacton->commit(); }cache(Exception $e){ $transacton->rollBack(); var_dump($e->getMessage()); }

 




注:本文為作者(44106-kangaroo) 看完魏羲教你學Yii2.0 視頻后所記,如有轉載請注明出處:http://www.cnblogs.com/chrdai/p/8006425.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM