目录
一、增删查改
二、验证规则
三、事务管理
四、名字空间。参考: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)复杂程度:
- $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的实例
官方文档
- $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();}
实际项目
- $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中已配置
- 'components'=>array(
- 'user'=>array('allowAutoLogin'=>true,),
- 'db'=>array("数据库连接参数"),
- )