Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

166 lines
5.0KB

  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. * @author Qiang Xue <qiang.xue@gmail.com>
  59. * @since 2.0
  60. */
  61. class SqlDataProvider extends BaseDataProvider
  62. {
  63. /**
  64. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  65. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  66. */
  67. public $db = 'db';
  68. /**
  69. * @var string the SQL statement to be used for fetching data rows.
  70. */
  71. public $sql;
  72. /**
  73. * @var array parameters (name=>value) to be bound to the SQL statement.
  74. */
  75. public $params = [];
  76. /**
  77. * @var string|callable the column that is used as the key of the data models.
  78. * This can be either a column name, or a callable that returns the key value of a given data model.
  79. *
  80. * If this is not set, the keys of the [[models]] array will be used.
  81. */
  82. public $key;
  83. /**
  84. * Initializes the DB connection component.
  85. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  86. * @throws InvalidConfigException if [[db]] is invalid.
  87. */
  88. public function init()
  89. {
  90. parent::init();
  91. $this->db = Instance::ensure($this->db, Connection::className());
  92. if ($this->sql === null) {
  93. throw new InvalidConfigException('The "sql" property must be set.');
  94. }
  95. }
  96. /**
  97. * @inheritdoc
  98. */
  99. protected function prepareModels()
  100. {
  101. $sort = $this->getSort();
  102. $pagination = $this->getPagination();
  103. if ($pagination === false && $sort === false) {
  104. return $this->db->createCommand($this->sql, $this->params)->queryAll();
  105. }
  106. $sql = $this->sql;
  107. $orders = [];
  108. $limit = $offset = null;
  109. if ($sort !== false) {
  110. $orders = $sort->getOrders();
  111. $pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
  112. if (preg_match($pattern, $sql, $matches)) {
  113. array_unshift($orders, new Expression($matches[1]));
  114. $sql = preg_replace($pattern, '', $sql);
  115. }
  116. }
  117. if ($pagination !== false) {
  118. $pagination->totalCount = $this->getTotalCount();
  119. $limit = $pagination->getLimit();
  120. $offset = $pagination->getOffset();
  121. }
  122. $sql = $this->db->getQueryBuilder()->buildOrderByAndLimit($sql, $orders, $limit, $offset);
  123. return $this->db->createCommand($sql, $this->params)->queryAll();
  124. }
  125. /**
  126. * @inheritdoc
  127. */
  128. protected function prepareKeys($models)
  129. {
  130. $keys = [];
  131. if ($this->key !== null) {
  132. foreach ($models as $model) {
  133. if (is_string($this->key)) {
  134. $keys[] = $model[$this->key];
  135. } else {
  136. $keys[] = call_user_func($this->key, $model);
  137. }
  138. }
  139. return $keys;
  140. } else {
  141. return array_keys($models);
  142. }
  143. }
  144. /**
  145. * @inheritdoc
  146. */
  147. protected function prepareTotalCount()
  148. {
  149. return 0;
  150. }
  151. }