yii2 資料庫和ActiveRecord

來源:互聯網
上載者:User

標籤: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);

 

  • find() 方法返回所有記錄;
$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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.