data-providers.md 4.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
Data providers
==============

Data provider abstracts data set via [[yii\data\DataProviderInterface]] and handles pagination and sorting.
It can be used by [grids](data-grid.md), [lists and other data widgets](data-widgets.md).

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

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

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

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

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

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

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

```php
32
$query = new Query();
33
$provider = new ActiveDataProvider([
34
    'query' => $query->from('post'),
35 36 37
    'pagination' => [
        'pageSize' => 20,
    ],
38 39 40 41 42 43
]);

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

44 45 46
Array data provider
-------------------

47 48
ArrayDataProvider implements a data provider based on a data array.

49
The [[yii\data\ArrayDataProvider::$allModels]] property contains all data models that may be sorted and/or paginated.
50
ArrayDataProvider will provide the data after sorting and/or pagination.
51
You may configure the [[yii\data\ArrayDataProvider::$sort]] and [[yii\data\ArrayDataProvider::$pagination]] properties to
52 53
customize the sorting and pagination behaviors.

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

Compared to `ActiveDataProvider`, `ArrayDataProvider` could be less efficient
60
because it needs to have [[yii\data\ArrayDataProvider::$allModels]] ready.
61 62 63 64

ArrayDataProvider may be used in the following way:

```php
65
$query = new Query();
66
$provider = new ArrayDataProvider([
67
    'allModels' => $query->from('post')->all(),
68 69 70 71 72 73 74 75 76 77 78 79 80 81
    '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.

82 83 84
SQL data provider
-----------------

85 86 87 88
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
89 90 91
[[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.
92 93 94 95 96

`SqlDataProvider` may be used in the following way:

```php
$count = Yii::$app->db->createCommand('
97
    SELECT COUNT(*) FROM user WHERE status=:status
98 99 100
', [':status' => 1])->queryScalar();

$dataProvider = new SqlDataProvider([
101
    'sql' => 'SELECT * FROM user WHERE status=:status',
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    '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();
```

124 125 126 127
> 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.
128

129 130 131

Implementing your own custom data provider
------------------------------------------
132

133
TBD