Yii Active Record



-- 准备查询条件

Represents(作为、代表) a query criteria(标准), such as conditions, ordering by, limit/offset. 详见 yiiframework.com

在 Model 使用 CDbCriteria 执行关联查询

$criteria=new CDbCriteria();

在 Controller 使用 CDbCriteria 执行关联查询

$criteria = new CDbCriteria;
// 使用关联模型
$criteria->with = 'author';
// 或者,手工编写关联
$criteria->join = 'LEFT JOIN author ON author_id=author.ID';
// 使用模型关联多表
$criteria->with = 'author, author.r_tbl'; // Model Author has a relation table r_tbl
$criteria->select = 'author.username as auther_username'; // And in your Post model declare..  "public $auther_username"
$criteria->group = 'GROUP BY ...';
$dataProvider=new CActiveDataProvider('Post', array(
    'criteria' => $criteria,



-- 提供视图数据

Implements a data provider based on ActiveRecord. CActiveDataProvider provides data in terms of ActiveRecord objects which are of class modelClass. It uses the AR CActiveRecord::findAll method to retrieve the data from database. The criteria property can be used to specify various query options. 详见 yiiframework.com

$dataProvider=new CActiveDataProvider('Post', array(
        'order'=>'create_time DESC',
        // 'order' and 'with' clauses have no meaning for the count query

// $dataProvider->getData() will return a list of Post objects


-- 分页器 Yii Cpagination API


function actionIndex(){
    $criteria=new CDbCriteria();
    $pages=new CPagination($count);

    // results per page

    $this->render('index', array(
    'models' => $models,
         'pages' => $pages


<?php foreach($models as $model): ?>
    // display a model
<?php endforeach; ?>

// display pagination
<?php $this->widget('CLinkPager', array(
    'pages' => $pages,
)) ?>