这开始介绍Zii组件之前,先简要介绍一下Yii支持的数据源接口 IDataProvider,IDataProvider主要功能是为UI组件如GridView,ListView等提供数据源,同时也支持数据的分页和排序。下图为Yii内置的三种数据源:
三种Data Provider的使用大同小异:
CActiveDataProvider 基于ActiveRecord, 它通过AR的CActiveRecord::findAll方法读取数据库记录,并通过criteria属性设置查询条件。
如:
$dataProvider=new CActiveDataProvider('Post', array( 'criteria'=>array( 'condition'=>'status=1', 'order'=>'create_time DESC', 'with'=>array('author'), ), 'pagination'=>array( 'pageSize'=>20, ), )); // $dataProvider->getData() will return a list of Post objects
$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll(); // or using: $rawData=User::model()->findAll(); $dataProvider=new CArrayDataProvider($rawData, array( 'id'=>'user', 'sort'=>array( 'attributes'=>array( 'id', 'username', 'email', ), ), 'pagination'=>array( 'pageSize'=>10, ), )); // $dataProvider->getData() will return a list of arrays.
$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM tbl_user')->queryScalar(); $sql='SELECT * FROM tbl_user'; $dataProvider=new CSqlDataProvider($sql, array( 'totalItemCount'=>$count, 'sort'=>array( 'attributes'=>array( 'id', 'username', 'email', ), ), 'pagination'=>array( 'pageSize'=>10, ), )); // $dataProvider->getData() will return a list of arrays.关于DataProvider详细文档可以参见 Yii文档