安静
PHP技术博客

140331 YII 数据库操作查询

CDbCriteria操作:

$criteria = new CDbCriteria;  
$criteria->alias = 't';  //table t,默认select='*';  
//一些public vars   
$criteria->select = 'id,parentid,name'; //代表了要查询的字段,默认select='*';    
$criteria->join = 'xxx'; //连接表    
$criteria->with = 'xxx'; //调用relations   $criteria->with = array('accounts','varchar');  
$criteria->with  = array('teacher'=>  
    array('select'=>'username,company_id',  
     'order'=>'teacher.username ASC')  
);  
$criteria->limit = 10;    //取1条数据,如果小于0,则不作处理    
$criteria->offset = 1;   //两条合并起来,则表示 limit 10 offset 1,或者代表了。limit 1,10    
$criteria->order = 'xxx DESC,XXX ASC' ;//排序条件    
$criteria->group = 'group 条件';    
$criteria->having = 'having 条件 ';    
$criteria->distinct = FALSE; //是否唯一查询  
users::model()->findAll($criteria);  

事务操作:

$transaction = Yii::app ()->db->beginTransaction ();
try {
    if (! $model->save ()) {
        throw new Exception ( 'exception message' );
    }
    $transaction->commit ();
} catch ( Exception $e ) {
    $transaction->rollback ();
}

插入操作:

$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();

在 Yii 中,可以通过以下两个行为类(Behavior)自动更新字段:

CTimestampBehavior – 标准 zii 行为类,自动填充日期和时间相关的属性
BlameableBehavior – 用户扩展,解压缩到 /path/to/components/behaviors
编辑 /path/to/models/.php 添加或编辑 behavior 函数

public function behaviors()
{
return array(
'CTimestampBehavior' => array(
'class' => 'zii.behaviors.CTimestampBehavior',
'createAttribute' => 'created_date',
'updateAttribute' => 'updated_date',
'setUpdateOnCreate' => true,
),
'BlameableBehavior' => array(
'class' => 'application.components.behaviors.BlameableBehavior',
'createdByColumn' => 'created_by', // optional
'updatedByColumn' => 'modified_by', // optional
),
);
}
赞(0) 打赏
未经允许不得转载:AJ's Blog » 140331 YII 数据库操作查询
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏