SqlDataProvider.php 5.3 KB

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