Before introducing Zii components, let’s briefly introduce the data source interface IDataProvider supported by Yii. The main function of IDataProvider is to provide data sources for UI components such as GridView, ListView, etc., and also supports paging and sorting of data. The following figure shows the three built-in data sources in Yii:
CActiveDataProvider Data source based on Active Record
CArraryDataProvider Data source based on array
CSqlDataProvider Data source based on SQL query
The use of the three Data Providers is similar:
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 objectsCArrayDataProvider 基于数组,其中属性 rawData设置原始数据,一般为数组或者DAO查询结果,如: $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.CSqlDataProvider 基于SQL查询,通过设置 sql 语句来配置,比如: $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.
The above is the content of the PHP development framework Yii Framework tutorial (28) Data Provider introduction, more related content Please pay attention to the PHP Chinese website (m.sbmmt.com)!