ActiveDataProvider.php 7.19 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\data;

10
use Yii;
11
use yii\base\InvalidConfigException;
12 13
use yii\base\InvalidParamException;
use yii\base\Model;
14
use yii\db\Query;
15
use yii\db\ActiveQuery;
16
use yii\db\Connection;
17 18

/**
19
 * ActiveDataProvider implements a data provider based on [[Query]] and [[ActiveQuery]].
20
 *
21
 * ActiveDataProvider provides data by performing DB queries using [[query]].
22
 *
23
 * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
24 25 26 27 28 29 30 31 32 33
 *
 * ~~~
 * $provider = new ActiveDataProvider(array(
 *     'query' => Post::find(),
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
34
 * $posts = $provider->getModels();
35 36
 * ~~~
 *
37 38 39
 * And the following example shows how to use ActiveDataProvider without ActiveRecord:
 *
 * ~~~
40
 * $query = new Query;
41
 * $provider = new ActiveDataProvider(array(
42
 *     'query' => $query->from('tbl_post'),
43 44 45 46 47 48
 *     'pagination' => array(
 *         'pageSize' => 20,
 *     ),
 * ));
 *
 * // get the posts in the current page
49
 * $posts = $provider->getModels();
50 51
 * ~~~
 *
52 53 54 55
 * @property integer $count The number of data models in the current page. This property is read-only.
 * @property array $keys The list of key values corresponding to [[models]]. Each data model in [[models]] is
 * uniquely identified by the corresponding key value in this array. This property is read-only.
 * @property array $models The list of data models in the current page. This property is read-only.
56 57
 * @property integer $totalCount Total number of possible data models.
 *
58 59 60 61 62 63
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveDataProvider extends DataProvider
{
	/**
64
	 * @var Query the query that is used to fetch data models and [[totalCount]]
65 66 67 68
	 * if it is not explicitly set.
	 */
	public $query;
	/**
69 70
	 * @var string|callable the column that is used as the key of the data models.
	 * This can be either a column name, or a callable that returns the key value of a given data model.
71
	 *
72
	 * If this is not set, the following rules will be used to determine the keys of the data models:
73 74
	 *
	 * - If [[query]] is an [[ActiveQuery]] instance, the primary keys of [[ActiveQuery::modelClass]] will be used.
75
	 * - Otherwise, the keys of the [[models]] array will be used.
76 77
	 *
	 * @see getKeys()
78
	 */
79
	public $key;
80 81 82 83 84
	/**
	 * @var Connection|string the DB connection object or the application component ID of the DB connection.
	 * If not set, the default DB connection will be used.
	 */
	public $db;
85

86
	private $_models;
87
	private $_keys;
88
	private $_totalCount;
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
	/**
	 * Initializes the DbCache component.
	 * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
	 * @throws InvalidConfigException if [[db]] is invalid.
	 */
	public function init()
	{
		parent::init();
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
			if (!$this->db instanceof Connection) {
				throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
			}
		}
	}

106
	/**
107 108
	 * Returns the number of data models in the current page.
	 * This is equivalent to `count($provider->models)`.
Qiang Xue committed
109
	 * When [[pagination]] is false, this is the same as [[totalCount]].
110
	 * @return integer the number of data models in the current page.
111
	 */
112
	public function getCount()
113
	{
114
		return count($this->getModels());
115 116 117
	}

	/**
118
	 * Returns the total number of data models.
Qiang Xue committed
119 120
	 * When [[pagination]] is false, this returns the same value as [[count]].
	 * If [[totalCount]] is not explicitly set, it will be calculated
121
	 * using [[query]] with a COUNT query.
122
	 * @return integer total number of possible data models.
123 124
	 * @throws InvalidConfigException
	 */
125
	public function getTotalCount()
126 127
	{
		if ($this->getPagination() === false) {
128
			return $this->getCount();
129
		} elseif ($this->_totalCount === null) {
130 131
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
132 133
			}
			$query = clone $this->query;
134
			$this->_totalCount = $query->limit(-1)->offset(-1)->count('*', $this->db);
135
		}
136
		return $this->_totalCount;
137 138 139
	}

	/**
140 141
	 * Sets the total number of data models.
	 * @param integer $value the total number of data models.
142
	 */
Qiang Xue committed
143
	public function setTotalCount($value)
144
	{
145
		$this->_totalCount = $value;
146 147 148
	}

	/**
149 150
	 * Returns the data models in the current page.
	 * @return array the list of data models in the current page.
151
	 * @throws InvalidConfigException if [[query]] is not set or invalid.
152
	 */
153
	public function getModels()
154
	{
155
		if ($this->_models === null) {
156 157 158 159 160 161 162 163
			if (!$this->query instanceof Query) {
				throw new InvalidConfigException('The "query" property must be an instance of Query or its subclass.');
			}
			if (($pagination = $this->getPagination()) !== false) {
				$pagination->totalCount = $this->getTotalCount();
				$this->query->limit($pagination->getLimit())->offset($pagination->getOffset());
			}
			if (($sort = $this->getSort()) !== false) {
164
				$this->query->addOrderBy($sort->getOrders());
165 166
			}
			$this->_models = $this->query->all($this->db);
167
		}
168
		return $this->_models;
169 170 171
	}

	/**
172 173
	 * Returns the key values associated with the data models.
	 * @return array the list of key values corresponding to [[models]]. Each data model in [[models]]
174 175
	 * is uniquely identified by the corresponding key value in this array.
	 */
176
	public function getKeys()
177
	{
178
		if ($this->_keys === null) {
179
			$this->_keys = array();
180
			$models = $this->getModels();
181
			if ($this->key !== null) {
182
				foreach ($models as $model) {
183
					if (is_string($this->key)) {
184
						$this->_keys[] = $model[$this->key];
185
					} else {
186
						$this->_keys[] = call_user_func($this->key, $model);
187 188 189
					}
				}
			} elseif ($this->query instanceof ActiveQuery) {
190 191 192 193 194
				/** @var \yii\db\ActiveRecord $class */
				$class = $this->query->modelClass;
				$pks = $class::primaryKey();
				if (count($pks) === 1) {
					$pk = $pks[0];
195 196
					foreach ($models as $model) {
						$this->_keys[] = $model[$pk];
197 198
					}
				} else {
199
					foreach ($models as $model) {
200 201
						$keys = array();
						foreach ($pks as $pk) {
202
							$keys[] = $model[$pk];
203 204 205 206 207
						}
						$this->_keys[] = json_encode($keys);
					}
				}
			} else {
208
				$this->_keys = array_keys($models);
209 210 211 212
			}
		}
		return $this->_keys;
	}
213 214

	/**
215 216 217
	 * Refreshes the data provider.
	 * After calling this method, if [[getModels()]], [[getKeys()]] or [[getTotalCount()]] is called again,
	 * they will re-execute the query and return the latest data available.
218
	 */
219
	public function refresh()
220
	{
221 222 223
		$this->_models = null;
		$this->_totalCount = null;
		$this->_keys = null;
224
	}
225 226

	/**
227
	 * @inheritdoc
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
	 */
	public function setSort($value)
	{
		parent::setSort($value);
		if (($sort = $this->getSort()) !== false && empty($sort->attributes) &&
			$this->query instanceof ActiveQuery) {

			/** @var Model $model */
			$model = new $this->query->modelClass;
			foreach($model->attributes() as $attribute) {
				$sort->attributes[$attribute] = array(
					'asc' => array($attribute => Sort::ASC),
					'desc' => array($attribute => Sort::DESC),
					'label' => $model->getAttributeLabel($attribute),
				);
			}
		}
	}
246
}