SqlDataProvider.php 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. use yii\db\Expression;
  12. use yii\di\Instance;
  13. /**
  14. * SqlDataProvider implements a data provider based on a plain SQL statement.
  15. *
  16. * SqlDataProvider provides data in terms of arrays, each representing a row of query result.
  17. *
  18. * Like other data providers, SqlDataProvider also supports sorting and pagination.
  19. * It does so by modifying the given [[sql]] statement with "ORDER BY" and "LIMIT"
  20. * clauses. You may configure the [[sort]] and [[pagination]] properties to
  21. * customize sorting and pagination behaviors.
  22. *
  23. * SqlDataProvider may be used in the following way:
  24. *
  25. * ```php
  26. * $count = Yii::$app->db->createCommand('
  27. * SELECT COUNT(*) FROM user WHERE status=:status
  28. * ', [':status' => 1])->queryScalar();
  29. *
  30. * $dataProvider = new SqlDataProvider([
  31. * 'sql' => 'SELECT * FROM user WHERE status=:status',
  32. * 'params' => [':status' => 1],
  33. * 'totalCount' => $count,
  34. * 'sort' => [
  35. * 'attributes' => [
  36. * 'age',
  37. * 'name' => [
  38. * 'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
  39. * 'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
  40. * 'default' => SORT_DESC,
  41. * 'label' => 'Name',
  42. * ],
  43. * ],
  44. * ],
  45. * 'pagination' => [
  46. * 'pageSize' => 20,
  47. * ],
  48. * ]);
  49. *
  50. * // get the user records in the current page
  51. * $models = $dataProvider->getModels();
  52. * ```
  53. *
  54. * Note: if you want to use the pagination feature, you must configure the [[totalCount]] property
  55. * to be the total number of rows (without pagination). And if you want to use the sorting feature,
  56. * you must configure the [[sort]] property so that the provider knows which columns can be sorted.
  57. *
  58. * For more details and usage information on SqlDataProvider, see the [guide article on data providers](guide:output-data-providers).
  59. *
  60. * @author Qiang Xue <qiang.xue@gmail.com>
  61. * @since 2.0
  62. */
  63. class SqlDataProvider extends BaseDataProvider
  64. {
  65. /**
  66. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  67. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  68. */
  69. public $db = 'db';
  70. /**
  71. * @var string the SQL statement to be used for fetching data rows.
  72. */
  73. public $sql;
  74. /**
  75. * @var array parameters (name=>value) to be bound to the SQL statement.
  76. */
  77. public $params = [];
  78. /**
  79. * @var string|callable the column that is used as the key of the data models.
  80. * This can be either a column name, or a callable that returns the key value of a given data model.
  81. *
  82. * If this is not set, the keys of the [[models]] array will be used.
  83. */
  84. public $key;
  85. /**
  86. * Initializes the DB connection component.
  87. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  88. * @throws InvalidConfigException if [[db]] is invalid.
  89. */
  90. public function init()
  91. {
  92. parent::init();
  93. $this->db = Instance::ensure($this->db, Connection::className());
  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. $sort = $this->getSort();
  104. $pagination = $this->getPagination();
  105. if ($pagination === false && $sort === false) {
  106. return $this->db->createCommand($this->sql, $this->params)->queryAll();
  107. }
  108. $sql = $this->sql;
  109. $orders = [];
  110. $limit = $offset = null;
  111. if ($sort !== false) {
  112. $orders = $sort->getOrders();
  113. $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
  114. if (preg_match($pattern, $sql, $matches)) {
  115. array_unshift($orders, new Expression($matches[1]));
  116. $sql = preg_replace($pattern, '', $sql);
  117. }
  118. }
  119. if ($pagination !== false) {
  120. $pagination->totalCount = $this->getTotalCount();
  121. $limit = $pagination->getLimit();
  122. $offset = $pagination->getOffset();
  123. }
  124. $sql = $this->db->getQueryBuilder()->buildOrderByAndLimit($sql, $orders, $limit, $offset);
  125. return $this->db->createCommand($sql, $this->params)->queryAll();
  126. }
  127. /**
  128. * @inheritdoc
  129. */
  130. protected function prepareKeys($models)
  131. {
  132. $keys = [];
  133. if ($this->key !== null) {
  134. foreach ($models as $model) {
  135. if (is_string($this->key)) {
  136. $keys[] = $model[$this->key];
  137. } else {
  138. $keys[] = call_user_func($this->key, $model);
  139. }
  140. }
  141. return $keys;
  142. } else {
  143. return array_keys($models);
  144. }
  145. }
  146. /**
  147. * @inheritdoc
  148. */
  149. protected function prepareTotalCount()
  150. {
  151. return 0;
  152. }
  153. }