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

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

6 7 8 9 10 11 12 13 14
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
--------------------

15 16 17 18 19 20
`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([
21 22 23 24
    'query' => Post::find(),
    'pagination' => [
        'pageSize' => 20,
    ],
25 26 27 28 29 30 31 32 33
]);

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

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'),
37 38 39
    'pagination' => [
        'pageSize' => 20,
    ],
40 41 42 43 44 45
]);

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

46 47 48
Array data provider
-------------------

49 50
ArrayDataProvider implements a data provider based on a data array.

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

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

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

ArrayDataProvider may be used in the following way:

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

84 85 86
SQL data provider
-----------------

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

`SqlDataProvider` may be used in the following way:

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

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

126 127 128 129
> 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.
130

131 132 133

Implementing your own custom data provider
------------------------------------------
134

135
TBD