ActiveDataProvider.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  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\base\InvalidConfigException;
  9. use yii\base\Model;
  10. use yii\db\ActiveQueryInterface;
  11. use yii\db\Connection;
  12. use yii\db\QueryInterface;
  13. use yii\di\Instance;
  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. * ```php
  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. * ```php
  36. * $query = new Query();
  37. * $provider = new ActiveDataProvider([
  38. * 'query' => $query->from('post'),
  39. * 'pagination' => [
  40. * 'pageSize' => 20,
  41. * ],
  42. * ]);
  43. *
  44. * // get the posts in the current page
  45. * $posts = $provider->getModels();
  46. * ```
  47. *
  48. * For more details and usage information on ActiveDataProvider, see the [guide article on data providers](guide:output-data-providers).
  49. *
  50. * @author Qiang Xue <qiang.xue@gmail.com>
  51. * @since 2.0
  52. */
  53. class ActiveDataProvider extends BaseDataProvider
  54. {
  55. /**
  56. * @var QueryInterface the query that is used to fetch data models and [[totalCount]]
  57. * if it is not explicitly set.
  58. */
  59. public $query;
  60. /**
  61. * @var string|callable the column that is used as the key of the data models.
  62. * This can be either a column name, or a callable that returns the key value of a given data model.
  63. *
  64. * If this is not set, the following rules will be used to determine the keys of the data models:
  65. *
  66. * - If [[query]] is an [[\yii\db\ActiveQuery]] instance, the primary keys of [[\yii\db\ActiveQuery::modelClass]] will be used.
  67. * - Otherwise, the keys of the [[models]] array will be used.
  68. *
  69. * @see getKeys()
  70. */
  71. public $key;
  72. /**
  73. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  74. * If not set, the default DB connection will be used.
  75. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  76. */
  77. public $db;
  78. /**
  79. * Initializes the DB connection component.
  80. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  81. * @throws InvalidConfigException if [[db]] is invalid.
  82. */
  83. public function init()
  84. {
  85. parent::init();
  86. if (is_string($this->db)) {
  87. $this->db = Instance::ensure($this->db, Connection::className());
  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. $query = clone $this->query;
  99. if (($pagination = $this->getPagination()) !== false) {
  100. $pagination->totalCount = $this->getTotalCount();
  101. if ($pagination->totalCount === 0) {
  102. return [];
  103. }
  104. $query->limit($pagination->getLimit())->offset($pagination->getOffset());
  105. }
  106. if (($sort = $this->getSort()) !== false) {
  107. $query->addOrderBy($sort->getOrders());
  108. }
  109. return $query->all($this->db);
  110. }
  111. /**
  112. * {@inheritdoc}
  113. */
  114. protected function prepareKeys($models)
  115. {
  116. $keys = [];
  117. if ($this->key !== null) {
  118. foreach ($models as $model) {
  119. if (is_string($this->key)) {
  120. $keys[] = $model[$this->key];
  121. } else {
  122. $keys[] = call_user_func($this->key, $model);
  123. }
  124. }
  125. return $keys;
  126. } elseif ($this->query instanceof ActiveQueryInterface) {
  127. /* @var $class \yii\db\ActiveRecordInterface */
  128. $class = $this->query->modelClass;
  129. $pks = $class::primaryKey();
  130. if (count($pks) === 1) {
  131. $pk = $pks[0];
  132. foreach ($models as $model) {
  133. $keys[] = $model[$pk];
  134. }
  135. } else {
  136. foreach ($models as $model) {
  137. $kk = [];
  138. foreach ($pks as $pk) {
  139. $kk[$pk] = $model[$pk];
  140. }
  141. $keys[] = $kk;
  142. }
  143. }
  144. return $keys;
  145. }
  146. return array_keys($models);
  147. }
  148. /**
  149. * {@inheritdoc}
  150. */
  151. protected function prepareTotalCount()
  152. {
  153. if (!$this->query instanceof QueryInterface) {
  154. 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.');
  155. }
  156. $query = clone $this->query;
  157. return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db);
  158. }
  159. /**
  160. * {@inheritdoc}
  161. */
  162. public function setSort($value)
  163. {
  164. parent::setSort($value);
  165. if (($sort = $this->getSort()) !== false && $this->query instanceof ActiveQueryInterface) {
  166. /* @var $modelClass Model */
  167. $modelClass = $this->query->modelClass;
  168. $model = $modelClass::instance();
  169. if (empty($sort->attributes)) {
  170. foreach ($model->attributes() as $attribute) {
  171. $sort->attributes[$attribute] = [
  172. 'asc' => [$attribute => SORT_ASC],
  173. 'desc' => [$attribute => SORT_DESC],
  174. 'label' => $model->getAttributeLabel($attribute),
  175. ];
  176. }
  177. } else {
  178. foreach ($sort->attributes as $attribute => $config) {
  179. if (!isset($config['label'])) {
  180. $sort->attributes[$attribute]['label'] = $model->getAttributeLabel($attribute);
  181. }
  182. }
  183. }
  184. }
  185. }
  186. public function __clone()
  187. {
  188. if (is_object($this->query)) {
  189. $this->query = clone $this->query;
  190. }
  191. parent::__clone();
  192. }
  193. }