ActiveDataProvider.php 4.94 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\db\ActiveQueryInterface;
12
use yii\base\InvalidConfigException;
13
use yii\base\Model;
14
use yii\db\Connection;
15
use yii\db\QueryInterface;
16 17

/**
Qiang Xue committed
18
 * ActiveDataProvider implements a data provider based on [[\yii\db\Query]] and [[\yii\db\ActiveQuery]].
19
 *
20
 * ActiveDataProvider provides data by performing DB queries using [[query]].
21
 *
22
 * The following is an example of using ActiveDataProvider to provide ActiveRecord instances:
23 24
 *
 * ~~~
Alexander Makarov committed
25
 * $provider = new ActiveDataProvider([
26
 *     'query' => Post::find(),
Alexander Makarov committed
27
 *     'pagination' => [
28
 *         'pageSize' => 20,
Alexander Makarov committed
29 30
 *     ],
 * ]);
31 32
 *
 * // get the posts in the current page
33
 * $posts = $provider->getModels();
34 35
 * ~~~
 *
36 37 38
 * And the following example shows how to use ActiveDataProvider without ActiveRecord:
 *
 * ~~~
39
 * $query = new Query;
Alexander Makarov committed
40
 * $provider = new ActiveDataProvider([
41
 *     'query' => $query->from('tbl_post'),
Alexander Makarov committed
42
 *     'pagination' => [
43
 *         'pageSize' => 20,
Alexander Makarov committed
44 45
 *     ],
 * ]);
46 47
 *
 * // get the posts in the current page
48
 * $posts = $provider->getModels();
49 50
 * ~~~
 *
51 52 53
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
54
class ActiveDataProvider extends BaseDataProvider
55 56
{
	/**
57
	 * @var QueryInterface the query that is used to fetch data models and [[totalCount]]
58 59 60 61
	 * if it is not explicitly set.
	 */
	public $query;
	/**
62 63
	 * @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.
64
	 *
65
	 * If this is not set, the following rules will be used to determine the keys of the data models:
66
	 *
67
	 * - If [[query]] is an [[\yii\db\ActiveQuery]] instance, the primary keys of [[\yii\db\ActiveQuery::modelClass]] will be used.
68
	 * - Otherwise, the keys of the [[models]] array will be used.
69 70
	 *
	 * @see getKeys()
71
	 */
72
	public $key;
73 74 75 76 77
	/**
	 * @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;
78

79
	/**
Alexander Makarov committed
80
	 * Initializes the DB connection component.
81 82 83 84 85 86 87 88
	 * 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);
Qiang Xue committed
89 90 91
			if ($this->db === null) {
				throw new InvalidConfigException('The "db" property must be a valid DB Connection application component.');
			}
92 93 94
		}
	}

95
	/**
Qiang Xue committed
96
	 * @inheritdoc
97
	 */
Qiang Xue committed
98
	protected function prepareModels()
99
	{
100 101
		if (!$this->query instanceof QueryInterface) {
			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.');
102
		}
Qiang Xue committed
103 104 105 106 107 108
		if (($pagination = $this->getPagination()) !== false) {
			$pagination->totalCount = $this->getTotalCount();
			$this->query->limit($pagination->getLimit())->offset($pagination->getOffset());
		}
		if (($sort = $this->getSort()) !== false) {
			$this->query->addOrderBy($sort->getOrders());
109
		}
Qiang Xue committed
110
		return $this->query->all($this->db);
111 112 113
	}

	/**
Qiang Xue committed
114
	 * @inheritdoc
115
	 */
Qiang Xue committed
116
	protected function prepareKeys($models)
117
	{
Alexander Makarov committed
118
		$keys = [];
Qiang Xue committed
119 120 121 122 123 124 125 126 127
		if ($this->key !== null) {
			foreach ($models as $model) {
				if (is_string($this->key)) {
					$keys[] = $model[$this->key];
				} else {
					$keys[] = call_user_func($this->key, $model);
				}
			}
			return $keys;
128
		} elseif ($this->query instanceof ActiveQueryInterface) {
Qiang Xue committed
129 130 131 132 133
			/** @var \yii\db\ActiveRecord $class */
			$class = $this->query->modelClass;
			$pks = $class::primaryKey();
			if (count($pks) === 1) {
				$pk = $pks[0];
134
				foreach ($models as $model) {
Qiang Xue committed
135
					$keys[] = $model[$pk];
136
				}
Qiang Xue committed
137 138
			} else {
				foreach ($models as $model) {
Alexander Makarov committed
139
					$kk = [];
Qiang Xue committed
140
					foreach ($pks as $pk) {
141
						$kk[$pk] = $model[$pk];
142
					}
143
					$keys[] = $kk;
144 145
				}
			}
Qiang Xue committed
146 147 148
			return $keys;
		} else {
			return array_keys($models);
149 150
		}
	}
151 152

	/**
Qiang Xue committed
153
	 * @inheritdoc
154
	 */
Qiang Xue committed
155
	protected function prepareTotalCount()
156
	{
157 158
		if (!$this->query instanceof QueryInterface) {
			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.');
Qiang Xue committed
159 160
		}
		$query = clone $this->query;
161
		return (int) $query->limit(-1)->offset(-1)->orderBy([])->count('*', $this->db);
162
	}
163 164

	/**
Qiang Xue committed
165
	 * @inheritdoc
166 167 168 169
	 */
	public function setSort($value)
	{
		parent::setSort($value);
170
		if (($sort = $this->getSort()) !== false && empty($sort->attributes) && $this->query instanceof ActiveQueryInterface) {
171 172
			/** @var Model $model */
			$model = new $this->query->modelClass;
173
			foreach ($model->attributes() as $attribute) {
Alexander Makarov committed
174
				$sort->attributes[$attribute] = [
175 176
					'asc' => [$attribute => SORT_ASC],
					'desc' => [$attribute => SORT_DESC],
177
					'label' => $model->getAttributeLabel($attribute),
Alexander Makarov committed
178
				];
179 180 181
			}
		}
	}
182
}