output-data-providers.md 4.58 KB
Newer Older
1 2 3
Data providers
==============

4
> Note: This section is under development.
Qiang Xue committed
5

6
Data provider abstracts data set via [[yii\data\DataProviderInterface]] and handles pagination and sorting.
Carsten Brandt committed
7
It can be used by [grids, lists and other data widgets](output-data-widgets.md).
8 9 10 11 12 13 14

In Yii there are three built-in data providers: [[yii\data\ActiveDataProvider]], [[yii\data\ArrayDataProvider]] and
[[yii\data\SqlDataProvider]].

Active data provider
--------------------

15
`ActiveDataProvider` provides data by performing DB queries using [[yii\db\Query]] and [[yii\db\ActiveQuery]].
16 17 18 19 20

The following is an example of using it to provide ActiveRecord instances:

```php
$provider = new ActiveDataProvider([
21 22 23 24
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
25 26 27 28
]);

// get the posts in the current page
$posts = $provider->getModels();
29
```
30 31 32 33

And the following example shows how to use ActiveDataProvider without ActiveRecord:

```php
34
$query = new Query();
35
$provider = new ActiveDataProvider([
36
    'query' => $query->from('post'),
ff committed
37 38 39 40 41 42 43
    'sort' => [
        // Set the default sort by name ASC and created_at DESC.
        'defaultOrder' => [
            'name' => SORT_ASC, 
            'created_at' => SORT_DESC
        ]
    ],
44 45 46
    'pagination' => [
        'pageSize' => 20,
    ],
47 48 49 50 51 52
]);

// get the posts in the current page
$posts = $provider->getModels();
```

53 54 55
Array data provider
-------------------

56 57
ArrayDataProvider implements a data provider based on a data array.

58
The [[yii\data\ArrayDataProvider::$allModels]] property contains all data models that may be sorted and/or paginated.
59
ArrayDataProvider will provide the data after sorting and/or pagination.
60
You may configure the [[yii\data\ArrayDataProvider::$sort]] and [[yii\data\ArrayDataProvider::$pagination]] properties to
61 62
customize the sorting and pagination behaviors.

63
Elements in the [[yii\data\ArrayDataProvider::$allModels]] array may be either objects (e.g. model objects)
64
or associative arrays (e.g. query results of DAO).
65
Make sure to set the [[yii\data\ArrayDataProvider::$key]] property to the name of the field that uniquely
66 67 68
identifies a data record or false if you do not have such a field.

Compared to `ActiveDataProvider`, `ArrayDataProvider` could be less efficient
69
because it needs to have [[yii\data\ArrayDataProvider::$allModels]] ready.
70 71 72 73

ArrayDataProvider may be used in the following way:

```php
74
$query = new Query();
75
$provider = new ArrayDataProvider([
76
    'allModels' => $query->from('post')->all(),
77 78 79 80 81 82 83 84 85 86 87 88 89 90
    'sort' => [
        'attributes' => ['id', 'username', 'email'],
    ],
    'pagination' => [
        'pageSize' => 10,
    ],
]);
// get the posts in the current page
$posts = $provider->getModels();
```

> Note: if you want to use the sorting feature, you must configure the [[sort]] property
so that the provider knows which columns can be sorted.

91 92 93
SQL data provider
-----------------

94 95 96 97
SqlDataProvider implements a data provider based on a plain SQL statement. It provides data in terms of arrays, each
representing a row of query result.

Like other data providers, SqlDataProvider also supports sorting and pagination. It does so by modifying the given
98 99 100
[[yii\data\SqlDataProvider::$sql]] statement with "ORDER BY" and "LIMIT" clauses. You may configure the
[[yii\data\SqlDataProvider::$sort]] and [[yii\data\SqlDataProvider::$pagination]] properties to customize sorting
and pagination behaviors.
101 102 103 104 105

`SqlDataProvider` may be used in the following way:

```php
$count = Yii::$app->db->createCommand('
106
    SELECT COUNT(*) FROM user WHERE status=:status
107 108 109
', [':status' => 1])->queryScalar();

$dataProvider = new SqlDataProvider([
110
    'sql' => 'SELECT * FROM user WHERE status=:status',
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
    'params' => [':status' => 1],
    'totalCount' => $count,
    'sort' => [
        'attributes' => [
            'age',
            'name' => [
                'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
                'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
                'default' => SORT_DESC,
                'label' => 'Name',
            ],
        ],
    ],
    'pagination' => [
        'pageSize' => 20,
    ],
]);

// get the user records in the current page
$models = $dataProvider->getModels();
```

133 134 135 136
> Note: if you want to use the pagination feature, you must configure the [[yii\data\SqlDataProvider::$totalCount]]
property to be the total number of rows (without pagination). And if you want to use the sorting feature,
you must configure the [[yii\data\SqlDataProvider::$sort]] property so that the provider knows which columns can
be sorted.
137

138 139 140

Implementing your own custom data provider
------------------------------------------
141

142
TBD