Yii Active Record

辅助类

CDbCriteria

-- 准备查询条件

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

在 Model 使用 CDbCriteria 执行关联查询

$criteria=new CDbCriteria();
$criteria->compare('status',Post::STATUS_ACTIVE);
$criteria->addInCondition('id',array(1,2,3,4,5,6));

在 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,
));

注:多次对相关表进行查询,可以得到相关表的属性,但占用更多资源。

CActiveDataProvider

-- 提供视图数据

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(
    'criteria'=>array(
        'condition'=>'status=1',
        'order'=>'create_time DESC',
        'with'=>array('author'),
    ),
    'countCriteria'=>array(
        'condition'=>'status=1',
        // 'order' and 'with' clauses have no meaning for the count query
    ),
    'pagination'=>array(
        'pageSize'=>20,
    ),
));

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

CPagination

-- 分页器 Yii Cpagination API

Controller

function actionIndex(){
    $criteria=new CDbCriteria();
    $count=Article::model()->count($criteria);
    $pages=new CPagination($count);

    // results per page
    $pages->pageSize=10;
    $pages->applyLimit($criteria);
    $models=Article::model()->findAll($criteria);

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

View:

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

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