You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 line
6.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\db\ActiveQueryInterface;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\Model;
  12. use yii\db\Connection;
  13. use yii\db\QueryInterface;
  14. use yii\di\Instance;
  15. /**
  16. * ActiveDataProvider implements a data provider based on [[\yii\db\Query]] and [[\yii\db\ActiveQuery]].
  17. *
  18. * ActiveDataProvider provides data by performing DB queries using [[query]].
  19. *
  20. * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
  21. *
  22. * ```php
  23. * $provider = new ActiveDataProvider([
  24. * 'query' => Post::find(),
  25. * 'pagination' => [
  26. * 'pageSize' => 20,
  27. * ],
  28. * ]);
  29. *
  30. * // get the posts in the current page
  31. * $posts = $provider->getModels();
  32. * ```
  33. *
  34. * And the following example shows how to use ActiveDataProvider without ActiveRecord:
  35. *
  36. * ```php
  37. * $query = new Query();
  38. * $provider = new ActiveDataProvider([
  39. * 'query' => $query->from('post'),
  40. * 'pagination' => [
  41. * 'pageSize' => 20,
  42. * ],
  43. * ]);
  44. *
  45. * // get the posts in the current page
  46. * $posts = $provider->getModels();
  47. * ```
  48. *
  49. * @author Qiang Xue <qiang.xue@gmail.com>
  50. * @since 2.0
  51. */
  52. class ActiveDataProvider extends BaseDataProvider
  53. {
  54. /**
  55. * @var QueryInterface the query that is used to fetch data models and [[totalCount]]
  56. * if it is not explicitly set.
  57. */
  58. public $query;
  59. /**
  60. * @var string|callable the column that is used as the key of the data models.
  61. * This can be either a column name, or a callable that returns the key value of a given data model.
  62. *
  63. * If this is not set, the following rules will be used to determine the keys of the data models:
  64. *
  65. * - If [[query]] is an [[\yii\db\ActiveQuery]] instance, the primary keys of [[\yii\db\ActiveQuery::modelClass]] will be used.
  66. * - Otherwise, the keys of the [[models]] array will be used.
  67. *
  68. * @see getKeys()
  69. */
  70. public $key;
  71. /**
  72. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  73. * If not set, the default DB connection will be used.
  74. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  75. */
  76. public $db;
  77. /**
  78. * Initializes the DB connection component.
  79. * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
  80. * @throws InvalidConfigException if [[db]] is invalid.
  81. */
  82. public function init()
  83. {
  84. parent::init();
  85. if (is_string($this->db)) {
  86. $this->db = Instance::ensure($this->db, Connection::className());
  87. }
  88. }
  89. /**
  90. * @inheritdoc
  91. */
  92. protected function prepareModels()
  93. {
  94. if (!$this->query instanceof QueryInterface) {
  95. 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.');
  96. }
  97. $query = clone $this->query;
  98. if (($pagination = $this->getPagination()) !== false) {
  99. $pagination->totalCount = $this->getTotalCount();
  100. $query->limit($pagination->getLimit())->offset($pagination->getOffset());
  101. }
  102. if (($sort = $this->getSort()) !== false) {
  103. $query->addOrderBy($sort->getOrders());
  104. }
  105. return $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 $class \yii\db\ActiveRecord */
  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 && $this->query instanceof ActiveQueryInterface) {
  163. /* @var $model Model */
  164. $model = new $this->query->modelClass;
  165. if (empty($sort->attributes)) {
  166. foreach ($model->attributes() as $attribute) {
  167. $sort->attributes[$attribute] = [
  168. 'asc' => [$attribute => SORT_ASC],
  169. 'desc' => [$attribute => SORT_DESC],
  170. 'label' => $model->getAttributeLabel($attribute),
  171. ];
  172. }
  173. } else {
  174. foreach ($sort->attributes as $attribute => $config) {
  175. if (!isset($config['label'])) {
  176. $sort->attributes[$attribute]['label'] = $model->getAttributeLabel($attribute);
  177. }
  178. }
  179. }
  180. }
  181. }
  182. }