SqlDataProvider.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\data;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. use yii\db\Connection;
  11. /**
  12. * SqlDataProvider implements a data provider based on a plain SQL statement.
  13. *
  14. * SqlDataProvider provides data in terms of arrays, each representing a row of query result.
  15. *
  16. * Like other data providers, SqlDataProvider also supports sorting and pagination.
  17. * It does so by modifying the given [[sql]] statement with "ORDER BY" and "LIMIT"
  18. * clauses. You may configure the [[sort]] and [[pagination]] properties to
  19. * customize sorting and pagination behaviors.
  20. *
  21. * SqlDataProvider may be used in the following way:
  22. *
  23. * ~~~
  24. * $count = Yii::$app->db->createCommand('
  25. * SELECT COUNT(*) FROM tbl_user WHERE status=:status
  26. * ', [':status' => 1])->queryScalar();
  27. *
  28. * $dataProvider = new SqlDataProvider([
  29. * 'sql' => 'SELECT * FROM tbl_user WHERE status=:status',
  30. * 'params' => [':status' => 1],
  31. * 'totalCount' => $count,
  32. * 'sort' => [
  33. * 'attributes' => [
  34. * 'age',
  35. * 'name' => [
  36. * 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
  37. * 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
  38. * 'default' => SORT_DESC,
  39. * 'label' => 'Name',
  40. * ],
  41. * ],
  42. * ],
  43. * 'pagination' => [
  44. * 'pageSize' => 20,
  45. * ],
  46. * ]);
  47. *
  48. * // get the user records in the current page
  49. * $models = $dataProvider->getModels();
  50. * ~~~
  51. *
  52. * Note: if you want to use the pagination feature, you must configure the [[totalCount]] property
  53. * to be the total number of rows (without pagination). And if you want to use the sorting feature,
  54. * you must configure the [[sort]] property so that the provider knows which columns can be sorted.
  55. *
  56. * @author Qiang Xue <[email protected]>
  57. * @since 2.0
  58. */
  59. class SqlDataProvider extends BaseDataProvider
  60. {
  61. /**
  62. * @var Connection|string the DB connection object or the application component ID of the DB connection.
  63. */
  64. public $db = 'db';
  65. /**
  66. * @var string the SQL statement to be used for fetching data rows.
  67. */
  68. public $sql;
  69. /**
  70. * @var array parameters (name=>value) to be bound to the SQL statement.
  71. */
  72. public $params = [];
  73. /**
  74. * @var string|callable the column that is used as the key of the data models.
  75. * This can be either a column name, or a callable that returns the key value of a given data model.
  76. *
  77. * If this is not set, the keys of the [[models]] array will be used.
  78. */
  79. public $key;
  80. /**
  81. * Initializes the DB connection component.
  82. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  83. * @throws InvalidConfigException if [[db]] is invalid.
  84. */
  85. public function init()
  86. {
  87. parent::init();
  88. if (is_string($this->db)) {
  89. $this->db = Yii::$app->getComponent($this->db);
  90. }
  91. if (!$this->db instanceof Connection) {
  92. throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
  93. }
  94. if ($this->sql === null) {
  95. throw new InvalidConfigException('The "sql" property must be set.');
  96. }
  97. }
  98. /**
  99. * @inheritdoc
  100. */
  101. protected function prepareModels()
  102. {
  103. $sql = $this->sql;
  104. $qb = $this->db->getQueryBuilder();
  105. if (($sort = $this->getSort()) !== false) {
  106. $orderBy = $qb->buildOrderBy($sort->getOrders());
  107. if (!empty($orderBy)) {
  108. $orderBy = substr($orderBy, 9);
  109. if (preg_match('/\s+order\s+by\s+[\w\s,\.]+$/i', $sql)) {
  110. $sql .= ', ' . $orderBy;
  111. } else {
  112. $sql .= ' ORDER BY ' . $orderBy;
  113. }
  114. }
  115. }
  116. if (($pagination = $this->getPagination()) !== false) {
  117. $pagination->totalCount = $this->getTotalCount();
  118. $sql .= ' ' . $qb->buildLimit($pagination->getLimit(), $pagination->getOffset());
  119. }
  120. return $this->db->createCommand($sql, $this->params)->queryAll();
  121. }
  122. /**
  123. * @inheritdoc
  124. */
  125. protected function prepareKeys($models)
  126. {
  127. $keys = [];
  128. if ($this->key !== null) {
  129. foreach ($models as $model) {
  130. if (is_string($this->key)) {
  131. $keys[] = $model[$this->key];
  132. } else {
  133. $keys[] = call_user_func($this->key, $model);
  134. }
  135. }
  136. return $keys;
  137. } else {
  138. return array_keys($models);
  139. }
  140. }
  141. /**
  142. * @inheritdoc
  143. */
  144. protected function prepareTotalCount()
  145. {
  146. return 0;
  147. }
  148. }