Yii2 使用 Active Record訪問和操作數據庫中的數據

Active Record 提供了⼀個⾯向對象的接⼝, ⽤以訪問和操作數據庫中的數據。 Active Record 類與數據庫表關聯, Active Record 實例對應於該表的⼀⾏, Active Record 實例的屬性表示該⾏中特定列的值。 你可以訪問
Active Record 屬性並調⽤ Active Record ⽅法來訪問和操作存儲在數據庫表中的數據, ⽽不⽤編寫原始 SQL 語句。

官⽹⽂檔:
https://www.yiichina.com/doc/guide/2.0/db-active-record#active-record
創建模型

namespace app\models;
use yii\db\ActiveRecord;
class Customer extends ActiveRecord
{
    const STATUS_INACTIVE = 0;
    const STATUS_ACTIVE = 1;
    /**
     * @return string Active Record 類關聯的數據庫表名稱
     */
    public static function tableName()
    {
        return '{{customer}}';
    }
}

框架表名的駝峯式爲模型名,?如 customer 對應的模型名爲 Customer
$customer = new Customer();
$customer->name = 'Lchiee';
$customer->save();
 

$values = [
    'name' => 'James',
    'email' => '[email protected]',
];

$customer = new Customer();
$customer->attributes = $values;
$customer->save();
塊賦值
刪除
$customer = Customer::findOne(123);
$customer->delete();
更新

$customer = Customer::findOne(1);
$customer->name = 'Lchiee Jk';
$customer->save(); //返回 boolean

// 沒有更新時返回 0
$customer->update(); //返回 int
批量更新
// UPDATE `customer` SET `status` = 1 WHERE `email` LIKE `%@example.com%`
Customer::updateAll(['status' => 1], ['like', 'email', '@example.com']);
// UPDATE `customer` SET `age` = `age` + 1
Customer::updateAllCounters(['age' => 1]);
模型查詢
// 獲取查詢結果
$customer = Customer::findOne();
//根據主鍵查詢 SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);
//條件查詢 SELECT * FROM `customer` WHERE `id` = 123 AND `status` = 1

$customer = Customer::findOne([
    'id' => 123,
    'status' => 1,
]);

//查詢多條 SELECT * FROM `customer` WHERE `id` IN (1, 2, 3)
$customer = Customer::findAll([1, 2, 3]);
// 查詢全表
$customer = Customer::findAll();
// 統計查詢 SELECT COUNT(*) FROM `customer` WHERE `status` = 1
$count = Customer::find()->where(['active' => 1])->count();
// 以 id 爲索引返回結果集
$count = Customer::find()->index('id')->all();
// (type = 1) AND (status = 2)
['type' => 1, 'status' => 2]
// (id IN (1, 2, 3)) AND (status = 2)
['id' => [1, 2, 3], 'status' => 2]
// status IS NULL
['status' => null]
// id=1 AND id=2
['and', 'id=1', 'id=2']
// type=1 AND (id=1 OR id=2)
['and', 'type=1', ['or', 'id=1', 'id=2']]
// (type IN (7, 8, 9) OR (id IN (1, 2, 3)))
['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]]
// NOT (attribute IS NULL)
['not', ['attribute' => null]]
// id >= 10
['>=', 'id', 10]

 


where && andWhere && orWhere
// id IN (1, 2, 3)
['in', 'id', [1, 2, 3]]
// (`card_type`, `source`) IN (('?陸身份證', '微信'), ('護照', '後臺'))
['in', ['card_type', 'source'], [['card_type' => '?陸身份證', 'source' => '微信'],
['card_type' => '護照', 'source' => '後臺']]]
// user_id IN (SELECT "id" FROM "users" WHERE "active"=1)
['in', 'user_id', (new Query())->select('id')->from('users')->where(['active' =>
1])]


`IN` && `NOT IN`
// name LIKE ‘%tester%'
['like', 'name', 'tester']
// name LIKE '%test%' AND name LIKE '%sample%'
['like', 'name', ['test', 'sample']]
// name LIKE '%tester'
['like', 'name', '%tester', false]
你也可以  'or like' 或者 'or not like' 來實現 `OR` 跟 `LIKE` 和 `NOT LIKE` 的組合
`LIKE` && `NOT LIKE`
// EXISTS (SELECT "id" FROM "users" WHERE "active"=1)
[‘exists', (new Query())->select('id')->from('users')->where(['active' => 1])]
`EXISTS` && `NOT EXISTS`


// id BETWEEN 1 AND 10
$customer = Customer::find()->where([‘between', 'id', 1, 10])->all();
`BETWEEN` && `NOT BETWEEN`
// SELECT EXISTS(SELECT * FROM `customer` WHERE `id`='123')
$customer = Customer::find()->where(['id' => '123'])->exists();
return $customer; // bool
exists
Tips: 當個值爲 null、空數組、空字符串或者?個只包含空?字符時,那麼它將被判定爲空值。
// SELECT * FROM `customer` WHERE `card_type`='?陸身份證'

$card_type = '?陸身份證';
$soure = '';
$customer = Customer::find()
    ->filterWhere([
        'card_type' => '身份證',
        'soure' => '',
    ])
    ->all();

filterWhere && andFilterWhere && orFilterWhere
假設 $card_type 和 $soure 來?於?戶的輸?
使?關聯數據
關聯關係
一對一
一對多
 多對多
 橋接一對多
 多態一對多關聯
 多態多對多關聯
聲明關聯關係

class Customer extends ActiveRecord
{
// ...
    public function getOrders()
    {
        return $this->hasMany(Orders::className(), ['customer_id' => 'id']);
    }
}
class Store extends ActiveRecord
{
// ...
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['id' => 'customer_id']);
    }
}

 
訪問關聯關係
// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);
// SELECT * FROM `order` WHERE `customer_id` = 123
$orders = $customer->orders;
// SELECT * FROM `order` WHERE `customer_id` = 123 AND `subtotal` > 200 ORDER BY
`id`
$orders = $customer->getOrders()
->where(['>', 'subtotal', 200])
->orderBy('id')
->all();


動態關聯查詢
延遲加載
// SELECT * FROM `customer` WHERE `id` = 123
$customer = Customer::findOne(123);
// SELECT * FROM `order` WHERE `customer_id` = 123
$orders = $customer->orders;
// 沒有 SQL 語句被執行
$orders2 = $customer->orders;
// SELECT * FROM `customer` LIMIT 100
$customers = Customer::find()->limit(100)->all();
foreach ($customers as $customer) {
// SELECT * FROM `order` WHERE `customer_id` = ...
$orders = $customer->orders;
}
But, 延遲加載….
// SELECT * FROM `customer` LIMIT 100;
// SELECT * FROM `orders` WHERE `customer_id` IN (...)
$customers = Customer::find()
->with('orders')
->limit(100)
->all();


foreach ($customers as $customer) {
// 沒有任何的 SQL 執行
$orders = $customer->orders;
}
即時加載
// 即時加載 "orders" and "country"
$customers = Customer::find()->with('orders', 'country')->all();
// 等同於使?數組語法 如下
$customers = Customer::find()->with(['orders', 'country'])->all();
即時加載多個
// 即時加載“訂單”和嵌套關係“orders.items”
$customers = Customer::find()->with('orders.items')->all();
嵌套即時加載
// 查找所有客戶,並帶上他們國家和活躍訂單
// SELECT * FROM `customer`
// SELECT * FROM `country` WHERE `id` IN (...)
// SELECT * FROM `order` WHERE `customer_id` IN (...) AND `status` = 1

$customers = Customer::find()->with([
    'country',
    'orders' => function ($query) {
        $query->andWhere(['status' => 1]);
    },
])->all();

自定義關聯查詢
提示: 如果你在即時加載的關聯中調用 select() 方法,你要確保在關聯聲明中引用 的列必須被
select。否則,相應的模型(Models)無 法被加載。
關聯關係的 JOIN 查詢
// SELECT `customer`.* FROM `customer`
// LEFT JOIN `order` ON `order`.`customer_id` = `customer`.`id`
// WHERE `order`.`status` = 1
// SELECT * FROM `order` WHERE `customer_id` IN (...)
$customers = Customer::find()
->select('customer.*')
->leftJoin('order', '`order`.`customer_id` = `customer`.`id`')
->where(['order.status' => 1])
->with('orders')
->all();
$customers = Customer::find()
->joinWith('orders')
->where(['order.status' => Order::STATUS_ACTIVE])
->all();


使用 joinWith
默認情況下, joinWith() 會使⽤ LEFT JOIN 去連接主表和關聯表。 你可以通過 $joinType 參
數指定不同的連接類型(⽐如 RIGHT JOIN)。 如果你想要的連接類型是 INNER JOIN,你可
以直接⽤ innerJoinWith() ⽅法代替。
 


使用innerJoinWith
$evaluate = $this->onlineRepairEvaluation()->find()->asArray()
->select(‘online_repair_evaluation.*, customer.id as customer_id,
project.name as project_name')
->addSelect(["CONCAT(building.name, '-', room.number) as room_name"])
->where(['online_repair_evaluation.id' => $id])
->innerJoinWith([
'onlineRepair.customer',
'onlineRepair.roomSplited.room',
'onlineRepair.roomSplited.room.building',
'onlineRepair.project'
])
->with(['projectManagerEvaluate', 'tags.evaluateTag', 'questions'])
->one();
以上介紹了yii2裏面的Active Record用法

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章