標籤:16px 生命週期 資料 mon soft model sample where 對象
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);
$model = Post::find()->where([‘status‘=>1])->all();$model = Post::findAll([‘status‘=>1]);
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 = ‘[email protected]‘$customer -> save(); // 等同於 $customer -> insert()
b、yii\db\ActiveRecord::update() // 更新
$customer = Customer::findOne($id);$customer -> email = ‘[email protected]‘$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 的生命週期
yii2 資料庫和ActiveRecord