-
目錄
一、增刪查改
二、驗證規則
三、事務管理
四、名字空間。參考:Yii數據庫操作——名字空間(named scopes)的三種用法
一、增刪查改
1,創建
$post = new Post;
$post->title = "";
$post->content = "";
$post->created_at = "CDbExpression('NOW()')";
$post->save();
(1) 插入后可立即獲得主鍵id。
$id = $post->id; // 前提是auto_increment
(2) 某一個字段的值為缺省值時,可以在models/Class.php中修改
Class Post extends CActiveRecord{
public $title = 'new title';
$post = new Post;
echo $post->title; // 輸出是: new title
}
(3) 使用CDbExpression
$post->create_time = new CDbExpression('NOW()');
2,查詢【待補充】
(1) 通過主鍵查詢
find("postID=:postID", array(':postID' => postID)
findByPk($id) // 單主鍵
(2) 通過非主鍵查詢
find("postID=:postID", array(':postID' => postID)
findAll( id = $id )
findAll( id IN ( $id ) )
3,更新【待補充】
先find,并將對應字段賦新值,再保存
可以通過CActiveRecord::isNewRecord來判斷是新建,還是更新。
4,刪除
(1) 如果是一條記錄
先找到后刪除
$post=Post::model->findByPk(10);
$post->delete();
直接通過主鍵刪除(類級別刪除,不需要先載入記錄)
Post::model->deleteByPk(10);
(2) 如果是多條記錄(類級別刪除,不需要先載入記錄)
Post::model->deleteAll();
二、驗證規則
驗證規則(Data validation)發生在調用save()方法的時候。驗證是基于在rules()方法中的定義。
if( $post->save() ){
// 驗證通過
} else {
// 驗證失敗。通過getErrors()返回錯誤信息。
}
獲取用戶從表單提交的數據
$post->title = $_POST['title'];
$post->content = $_POST['content'];
$post->save();
如果多了,可以通過下面的方式減輕(alleviate)復雜程度:Php代碼- $post->attributes = $_POST['Post'];
- $post->save();
- //類似于:
- foreach($_POST['Post'] as $name=>$value){
- if($name is a safe attribute)
- $model->$name = $value;
- }
$post->attributes = $_POST['Post'];$post->save();//類似于:foreach($_POST['Post'] as $name=>$value){ if($name is a safe attribute) $model->$name = $value;}
注意:里面的驗證檢驗非常重要,否則用戶可能繞過授權。
三、事務管理
dbConnection是CDbConnection的實例
官方文檔Php代碼- $model = Post::model();
- $transaction = $model->dbConnection->beginTransaction();
- try{
- $post = $model->findByPk(10);
- $post->title = 'new post title';
- $post->save();
- $transaction->commit();
- } catch (Exception $e){
- $transaction->rollback();
- }
$model = Post::model();$transaction = $model->dbConnection->beginTransaction();try{ $post = $model->findByPk(10); $post->title = 'new post title'; $post->save(); $transaction->commit();} catch (Exception $e){ $transaction->rollback();}
實際項目Php代碼- $trans = Yii::app()->db->beginTransaction();
- try {
- $manufacturer = new Manufacturer();
- $manufacturer->name = $name;
- $manufacturer->email = $email;
- $manufacturer->save();
- $trans->commit();
- } catch (Exception $e) {
- $trans->rollback();
- $this->response(array('status' => 1, 'msg' => $e->getMessage()));
- }
$trans = Yii::app()->db->beginTransaction();try { $manufacturer = new Manufacturer(); $manufacturer->name = $name; $manufacturer->email = $email; $manufacturer->save(); $trans->commit();} catch (Exception $e) { $trans->rollback(); $this->response(array('status' => 1, 'msg' => $e->getMessage())); }
其實使用的時候跟凡客體的我是凡客或淘寶體的親一樣。
注:Yii::app()后面的db在../config/main.php中已配置Php代碼- 'components'=>array(
- 'user'=>array('allowAutoLogin'=>true,),
- 'db'=>array("數據庫連接參數"),
- )