ActiveDataProvider.php 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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\db\ActiveQueryInterface;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\Model;
  12. use yii\db\Connection;
  13. use yii\db\QueryInterface;
  14. /**
  15. * ActiveDataProvider implements a data provider based on [[\yii\db\Query]] and [[\yii\db\ActiveQuery]].
  16. *
  17. * ActiveDataProvider provides data by performing DB queries using [[query]].
  18. *
  19. * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
  20. *
  21. * ~~~
  22. * $provider = new ActiveDataProvider([
  23. * 'query' => Post::find(),
  24. * 'pagination' => [
  25. * 'pageSize' => 20,
  26. * ],
  27. * ]);
  28. *
  29. * // get the posts in the current page
  30. * $posts = $provider->getModels();
  31. * ~~~
  32. *
  33. * And the following example shows how to use ActiveDataProvider without ActiveRecord:
  34. *
  35. * ~~~
  36. * $query = new Query;
  37. * $provider = new ActiveDataProvider([
  38. * 'query' => $query->from('tbl_post'),
  39. * 'pagination' => [
  40. * 'pageSize' => 20,
  41. * ],
  42. * ]);
  43. *
  44. * // get the posts in the current page
  45. * $posts = $provider->getModels();
  46. * ~~~
  47. *
  48. * @author Qiang Xue <[email protected]>
  49. * @since 2.0
  50. */
  51. class ActiveDataProvider extends BaseDataProvider
  52. {
  53. /**
  54. * @var QueryInterface the query that is used to fetch data models and [[totalCount]]
  55. * if it is not explicitly set.
  56. */
  57. public $query;
  58. /**
  59. * @var string|callable the column that is used as the key of the data models.
  60. * This can be either a column name, or a callable that returns the key value of a given data model.
  61. *
  62. * If this is not set, the following rules will be used to determine the keys of the data models:
  63. *
  64. * - If [[query]] is an [[ActiveQuery]] instance, the primary keys of [[ActiveQuery::modelClass]] will be used.
  65. * - Otherwise, the keys of the [[models]] array will be used.
  66. *
  67. * @see getKeys()
  68. */
  69. public $key;
  70. /**
  71. * @var Connection|string the DB connection object or the application component ID of the DB connection.
  72. * If not set, the default DB connection will be used.
  73. */
  74. public $db;
  75. /**
  76. * Initializes the DB connection component.
  77. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  78. * @throws InvalidConfigException if [[db]] is invalid.
  79. */
  80. public function init()
  81. {
  82. parent::init();
  83. if (is_string($this->db)) {
  84. $this->db = Yii::$app->getComponent($this->db);
  85. if ($this->db === null) {
  86. throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
  87. }
  88. }
  89. }
  90. /**
  91. * @inheritdoc
  92. */
  93. protected function prepareModels()
  94. {
  95. if (!$this->query instanceof QueryInterface) {
  96. throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
  97. }
  98. if (($pagination = $this->getPagination()) !== false) {
  99. $pagination->totalCount = $this->getTotalCount();
  100. $this->query->limit($pagination->getLimit())->offset($pagination->getOffset());
  101. }
  102. if (($sort = $this->getSort()) !== false) {
  103. $this->query->addOrderBy($sort->getOrders());
  104. }
  105. return $this->query->all($this->db);
  106. }
  107. /**
  108. * @inheritdoc
  109. */
  110. protected function prepareKeys($models)
  111. {
  112. $keys = [];
  113. if ($this->key !== null) {
  114. foreach ($models as $model) {
  115. if (is_string($this->key)) {
  116. $keys[] = $model[$this->key];
  117. } else {
  118. $keys[] = call_user_func($this->key, $model);
  119. }
  120. }
  121. return $keys;
  122. } elseif ($this->query instanceof ActiveQueryInterface) {
  123. /** @var \yii\db\ActiveRecord $class */
  124. $class = $this->query->modelClass;
  125. $pks = $class::primaryKey();
  126. if (count($pks) === 1) {
  127. $pk = $pks[0];
  128. foreach ($models as $model) {
  129. $keys[] = $model[$pk];
  130. }
  131. } else {
  132. foreach ($models as $model) {
  133. $kk = [];
  134. foreach ($pks as $pk) {
  135. $kk[$pk] = $model[$pk];
  136. }
  137. $keys[] = $kk;
  138. }
  139. }
  140. return $keys;
  141. } else {
  142. return array_keys($models);
  143. }
  144. }
  145. /**
  146. * @inheritdoc
  147. */
  148. protected function prepareTotalCount()
  149. {
  150. if (!$this->query instanceof QueryInterface) {
  151. throw new InvalidConfigException('The "query" property must be an instance of a class that implements the QueryInterface e.g. yii\db\Query or its subclasses.');
  152. }
  153. $query = clone $this->query;
  154. return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db);
  155. }
  156. /**
  157. * @inheritdoc
  158. */
  159. public function setSort($value)
  160. {
  161. parent::setSort($value);
  162. if (($sort = $this->getSort()) !== false && empty($sort->attributes) && $this->query instanceof ActiveQueryInterface) {
  163. /** @var Model $model */
  164. $model = new $this->query->modelClass;
  165. foreach ($model->attributes() as $attribute) {
  166. $sort->attributes[$attribute] = [
  167. 'asc' => [$attribute => SORT_ASC],
  168. 'desc' => [$attribute => SORT_DESC],
  169. 'label' => $model->getAttributeLabel($attribute),
  170. ];
  171. }
  172. }
  173. }
  174. }