`
空洞的世界
  • 浏览: 49375 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

yii 常用的对数据库处理方式

阅读更多
[size=large]1 .Select:  常用几种方法

// find the first row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);

$criteria=new CDbCriteria;
$criteria->select='title';  // only select the 'title' column
$criteria->condition='postID=:postID';
$criteria->params=array(':postID'=>10);
$post=Post::model()->find($criteria);

$post=Post::model()->find(array(
    'select'=>'title',
    'condition'=>'postID=:postID',
    'params'=>array(':postID'=>10),
));

// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()->findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()->findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);

// get the number of rows satisfying the specified condition
$n=Post::model()->count($condition,$params);
// get the number of rows using the specified SQL statement
$n=Post::model()->countBySql($sql,$params);
// check if there is at least a row satisfying the specified condition
$exists=Post::model()->exists($condition,$params);


2.常用的修改方式--update

// update the rows matching the specified condition
Post::model()->updateAll($attributes,$condition,$params);
// update the rows matching the specified condition and primary key(s)
Post::model()->updateByPk($pk,$attributes,$condition,$params);
// update counter columns in the rows satisfying the specified conditions
Post::model()->updateCounters($counters,$condition,$params);


3.常用的删除方式--delete

$post=Post::model()->findByPk(10); // assuming there is a post whose ID is 10
$post->delete();

// delete the rows matching the specified condition
Post::model()->deleteAll($condition,$params);
// delete the rows matching the specified condition and primary key(s)
Post::model()->deleteByPk($pk,$condition,$params);


4.常用的事物--innodb

    $model=Post::model();
    $transaction=$model->dbConnection->beginTransaction();
    try
    {
        // find and save are two steps which may be intervened by another request
        // we therefore use a transaction to ensure consistency and integrity
        $post=$model->findByPk(10);
        $post->title='new post title';
        $post->save();
        $transaction->commit();
    }
    catch(Exception $e)
    {
        $transaction->rollBack();
    }


希望对你们有帮助![/size]
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics