Home > Backend Development > PHP Tutorial > PHP development framework Yii Framework tutorial (28) Introduction to Data Provider

PHP development framework Yii Framework tutorial (28) Introduction to Data Provider

黄舟
Release: 2023-03-05 09:10:02
Original
1332 people have browsed it

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:

PHP development framework Yii Framework tutorial (28) Introduction to 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 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.
Copy after login

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 (www.php.cn)!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template