首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

Yii 1.x 模型詳解:CActiveRecord 與 CFormModel 完整指南

     編輯:PHP 相關知識

兩大模型體系

Yii 實現兩種模型,均繼承 CModel:

  • CActiveRecord (AR):對應數據庫表,封裝 CRUD、關聯、驗證、業務邏輯,核心業務首選。
  • CFormModel:對應表單輸入,僅在內存驗證、處理,不直接持久化(或輔助 AR 存儲)。

一、CActiveRecord 實戰

1. 聲明模型

class Post extends CActiveRecord {
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
    public function tableName() { return '{{post}}'; } // {{}} 自動替換表前綴
    public function primaryKey() { return 'id'; }
}

2. 常用操作

操作代碼示例
新增$p=new Post; $p->title='t'; $p->save();
查詢單條Post::model()->findByPk(10) / findByAttributes(['title'=>'abc'])
查詢多條Post::model()->findAll($criteria) / findAllBySql()
更新Post::model()->updateAll(['title'=>'new'], 'id=1')
刪除$p=Post::model()->findByPk(10); $p->delete();
事務$tx=$model->dbConnection->beginTransaction(); ... $tx->commit();

3. 進階:CDbCriteria 構建複雜查詢

$criteria = new CDbCriteria();
$criteria->select = 'title';
$criteria->condition = 'postID=:pid';
$criteria->params = [':pid'=>10];
$post = Post::model()->find($criteria);

二、CFormModel 表單模型

1. 定義與驗證規則

class LoginForm extends CFormModel {
    public $username, $password;
    public $rememberMe = false;

    public function rules() {
        return [
            ['username, password', 'required'],
            ['rememberMe', 'boolean'],
            ['password', 'authenticate'], // 自定義驗證方法
        ];
    }

    public function authenticate($attr, $params) {
        if (!$this->hasErrors()) {
            $identity = new UserIdentity($this->username, $this->password);
            if (!$identity->authenticate())
                $this->addError('password', '密碼錯誤');
        }
    }
}

2. 安全屬性與批量賦值

僅出現在驗證規則中的屬性才是「安全」的,允許 $model->attributes = $_POST['LoginForm'] 批量賦值。需暴露無驗證屬性時用 ['content', 'safe'];需排除用 ['permission', 'unsafe']。

3. 視圖中渲染表單

<?php $form=$this->beginWidget('CActiveForm'); ?>
    <?= $form->labelEx($model,'username') ?>
    <?= $form->textField($model,'username') ?>
    <?= $form->error($model,'username') ?>
    <?= $form->labelEx($model,'password') ?>
    <?= $form->passwordField($model,'password') ?>
    <?= $form->error($model,'password') ?>
    <?= CHtml::submitButton('登錄') ?>
<?php $this->endWidget(); ?>

關鍵配置:數據庫連接與日誌

'db'=>[
    'connectionString'=>'mysql:host=localhost;dbname=oss',
    'username'=>'root', 'password'=>'hahaha', 'charset'=>'utf8',
    'tablePrefix'=>'oss_', 'emulatePrepare'=>true,
],
'log'=>[
    'class'=>'CLogRouter',
    'routes'=>[
        ['class'=>'CWebLogRoute', 'levels'=>'trace, info'], // 頁面底部顯示 SQL
    ],
],

總結

AR 模型承擔核心業務與持久化,表單模型處理輸入驗證與臨時數據。善用 rules()、safe/unsafe、CDbCriteria、事務,能構建健壯、安全的數據層。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved