編輯 protected/config/main.php,取消註釋 MySQL 連接配置並修改參數:
'components' => array(
'db' => array(
'connectionString' => 'mysql:host=localhost;dbname=phplampDB',
'emulatePrepare' => true,
'username' => 'phplamp',
'password' => '1234',
'charset' => 'utf8',
'tablePrefix' => '',
),
),
路徑:protected/tests/unit/DbTest.php
<?php
class DbTest extends CTestCase {
public function testConnection() {
$this->assertNotEquals(NULL, Yii::app()->db);
}
}
cd protected/tests
phpunit unit/DbTest.php
輸出 OK (1 test, 1 assertion) 表示連接正常。
假設模型 User 對應表 tbl_user,主鍵 id。
updateByPk() (適合批量/無需實例化)$id = 123; // 或 array(1,2,3) 批量
$attributes = array('username' => 'yiistudy', 'email' => 'test@example.com');
$condition = 'status=:status';
$params = array(':status' => 1);
$count = User::model()->updateByPk($id, $attributes, $condition, $params);
if ($count > 0) {
echo "更新成功,影響行數: $count";
} else {
echo "更新失敗或無符合條件記錄";
}
參數說明:$id 主鍵值/陣列;$attributes 列名=>值陣列;$condition 可選 WHERE 條件;$params 參數綁定。
update() (適合業務邏輯複雜/驗證)$model = User::model()->findByPk(123);
if ($model !== null) {
$model->username = 'yiistudy';
$model->password = 'mysql'; // 假設有加密邏輯在 beforeSave()
// 僅更新指定屬性,跳過未變更欄位
$count = $model->update(array('username', 'password'));
if ($count > 0) {
echo "更新成功";
} else {
echo "無數據變更或更新失敗";
}
} else {
echo "記錄不存在";
}
差異點:
update() 觸發 beforeValidate、afterValidate、beforeSave、afterSave 等生命週期事件,執行驗證規則。updateByPk() 直擊 SQL,不觸發模型事件,性能略高,但繞過業務邏輯。DbTest,持續集成管道必跑。$params 陣列防 SQL 注入,避免字串拼接。Yii::app()->db->beginTransaction() 管理事務。version 欄位,updateByPk($id, $attr, 'version=:v', array(':v'=>$oldVersion)) 實現樂觀鎖。updateAll() 或分塊處理,避免單次 SQL 過大。