ActiveQuery.php 10.7 KB
Newer Older
Qiang Xue committed
1 2
<?php
/**
Qiang Xue committed
3
 * ActiveQuery class file.
Qiang Xue committed
4 5 6
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
Qiang Xue committed
7
 * @copyright Copyright &copy; 2008 Yii Software LLC
Qiang Xue committed
8 9 10
 * @license http://www.yiiframework.com/license/
 */

Qiang Xue committed
11
namespace yii\db;
Qiang Xue committed
12

Qiang Xue committed
13 14 15 16
use yii\db\Connection;
use yii\db\Command;
use yii\db\QueryBuilder;
use yii\db\Expression;
Qiang Xue committed
17

Qiang Xue committed
18 19 20 21 22 23 24 25 26 27
/**
 * ActiveQuery represents a DB query associated with an Active Record class.
 *
 * ActiveQuery instances are usually created by [[ActiveRecord::find()]], [[ActiveRecord::findBySql()]]
 * and [[ActiveRecord::count()]].
 *
 * ActiveQuery mainly provides the following methods to retrieve the query results:
 *
 * - [[one()]]: returns a single record populated with the first row of data.
 * - [[all()]]: returns all records based on the query results.
28 29 30 31 32 33
 * - [[count()]]: returns the number of records.
 * - [[sum()]]: returns the sum over the specified column.
 * - [[average()]]: returns the average over the specified column.
 * - [[min()]]: returns the min over the specified column.
 * - [[max()]]: returns the max over the specified column.
 * - [[scalar()]]: returns the value of the first column in the first row of the query result.
Qiang Xue committed
34 35 36 37 38 39 40
 * - [[exists()]]: returns a value indicating whether the query result has data or not.
 *
 * Because ActiveQuery extends from [[Query]], one can use query methods, such as [[where()]],
 * [[orderBy()]] to customize the query options.
 *
 * ActiveQuery also provides the following additional query options:
 *
Qiang Xue committed
41 42 43
 * - [[with()]]: list of relations that this query should be performed with.
 * - [[indexBy()]]: the name of the column by which the query result should be indexed.
 * - [[asArray()]]: whether to return each record as an array.
Qiang Xue committed
44 45 46 47 48 49 50 51 52 53
 *
 * These options can be configured using methods of the same name. For example:
 *
 * ~~~
 * $customers = Customer::find()->with('orders')->asArray()->all();
 * ~~~
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
54
class ActiveQuery extends Query
Qiang Xue committed
55 56 57 58 59 60 61 62
{
	/**
	 * @var string the name of the ActiveRecord class.
	 */
	public $modelClass;
	/**
	 * @var array list of relations that this query should be performed with
	 */
Qiang Xue committed
63
	public $with;
Qiang Xue committed
64
	/**
Qiang Xue committed
65
	 * @var string the name of the column by which query results should be indexed by.
Qiang Xue committed
66
	 * This is only used when the query result is returned as an array when calling [[all()]].
Qiang Xue committed
67
	 */
Qiang Xue committed
68
	public $indexBy;
Qiang Xue committed
69 70 71 72 73 74 75 76 77 78 79 80
	/**
	 * @var boolean whether to return each record as an array. If false (default), an object
	 * of [[modelClass]] will be created to represent each record.
	 */
	public $asArray;
	/**
	 * @var string the SQL statement to be executed for retrieving AR records.
	 * This is set by [[ActiveRecord::findBySql()]].
	 */
	public $sql;


81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	/**
	 * PHP magic method.
	 * This method allows calling static method defined in [[modelClass]] via this query object.
	 * It is mainly implemented for supporting the feature of scope.
	 * @param string $name the method name to be called
	 * @param array $params the parameters passed to the method
	 * @return mixed the method return result
	 */
	public function __call($name, $params)
	{
		if (method_exists($this->modelClass, $name)) {
			array_unshift($params, $this);
			return call_user_func_array(array($this->modelClass, $name), $params);
		} else {
			return parent::__call($name, $params);
		}
	}

Qiang Xue committed
99 100 101 102 103 104
	/**
	 * Executes query and returns all results as an array.
	 * @return array the query results. If the query results in nothing, an empty array will be returned.
	 */
	public function all()
	{
Qiang Xue committed
105 106
		$command = $this->createCommand();
		$rows = $command->queryAll();
107 108 109
		if ($rows !== array()) {
			$models = $this->createModels($rows);
			if (!empty($this->with)) {
Qiang Xue committed
110
				$this->populateRelations($models, $this->with);
111 112 113
			}
			return $models;
		} else {
Qiang Xue committed
114 115
			return array();
		}
Qiang Xue committed
116 117 118 119
	}

	/**
	 * Executes query and returns a single row of result.
Qiang Xue committed
120 121
	 * @return ActiveRecord|array|null a single row of query result. Depending on the setting of [[asArray]],
	 * the query result may be either an array or an ActiveRecord object. Null will be returned
Qiang Xue committed
122 123 124 125
	 * if the query results in nothing.
	 */
	public function one()
	{
Qiang Xue committed
126 127
		$command = $this->createCommand();
		$row = $command->queryRow();
128
		if ($row !== false && !$this->asArray) {
Qiang Xue committed
129
			/** @var $class ActiveRecord */
Qiang Xue committed
130
			$class = $this->modelClass;
Qiang Xue committed
131 132
			$model = $class::create($row);
			if (!empty($this->with)) {
Qiang Xue committed
133
				$models = array($model);
Qiang Xue committed
134
				$this->populateRelations($models, $this->with);
Qiang Xue committed
135
				$model = $models[0];
Qiang Xue committed
136 137
			}
			return $model;
138 139
		} else {
			return $row === false ? null : $row;
Qiang Xue committed
140
		}
Qiang Xue committed
141 142
	}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
	/**
	 * Returns the number of records.
	 * @param string $q the COUNT expression. Defaults to '*'.
	 * Make sure you properly quote column names.
	 * @return integer number of records
	 */
	public function count($q = '*')
	{
		$this->select = array("COUNT($q)");
		return $this->createCommand()->queryScalar();
	}

	/**
	 * Returns the sum of the specified column values.
	 * @param string $q the column name or expression.
	 * Make sure you properly quote column names.
	 * @return integer the sum of the specified column values
	 */
	public function sum($q)
	{
		$this->select = array("SUM($q)");
		return $this->createCommand()->queryScalar();
	}

	/**
	 * Returns the average of the specified column values.
	 * @param string $q the column name or expression.
	 * Make sure you properly quote column names.
	 * @return integer the average of the specified column values.
	 */
	public function average($q)
	{
		$this->select = array("AVG($q)");
		return $this->createCommand()->queryScalar();
	}

	/**
	 * Returns the minimum of the specified column values.
	 * @param string $q the column name or expression.
	 * Make sure you properly quote column names.
	 * @return integer the minimum of the specified column values.
	 */
	public function min($q)
	{
		$this->select = array("MIN($q)");
		return $this->createCommand()->queryScalar();
	}

	/**
	 * Returns the maximum of the specified column values.
	 * @param string $q the column name or expression.
	 * Make sure you properly quote column names.
	 * @return integer the maximum of the specified column values.
	 */
	public function max($q)
	{
		$this->select = array("MAX($q)");
		return $this->createCommand()->queryScalar();
	}

Qiang Xue committed
203
	/**
Qiang Xue committed
204
	 * Returns the query result as a scalar value.
Qiang Xue committed
205 206
	 * The value returned will be the first column in the first row of the query results.
	 * @return string|boolean the value of the first column in the first row of the query result.
Qiang Xue committed
207
	 * False is returned if the query result is empty.
Qiang Xue committed
208
	 */
209
	public function scalar()
Qiang Xue committed
210
	{
Qiang Xue committed
211
		return $this->createCommand()->queryScalar();
Qiang Xue committed
212 213 214
	}

	/**
Qiang Xue committed
215 216
	 * Returns a value indicating whether the query result contains any row of data.
	 * @return boolean whether the query result contains any row of data.
Qiang Xue committed
217 218 219
	 */
	public function exists()
	{
Qiang Xue committed
220
		$this->select = array(new Expression('1'));
221
		return $this->scalar() !== false;
Qiang Xue committed
222 223 224
	}

	/**
Qiang Xue committed
225
	 * Creates a DB command that can be used to execute this query.
Qiang Xue committed
226 227
	 * @param Connection $db the DB connection used to create the DB command.
	 * If null, the DB connection returned by [[modelClass]] will be used.
Qiang Xue committed
228
	 * @return Command the created DB command instance.
Qiang Xue committed
229
	 */
Qiang Xue committed
230
	public function createCommand($db = null)
Qiang Xue committed
231
	{
Qiang Xue committed
232
		/** @var $modelClass ActiveRecord */
Qiang Xue committed
233
		$modelClass = $this->modelClass;
Qiang Xue committed
234
		if ($db === null) {
Qiang Xue committed
235
			$db = $modelClass::getDb();
Qiang Xue committed
236
		}
Qiang Xue committed
237 238 239 240 241 242 243
		if ($this->sql === null) {
			if ($this->from === null) {
				$tableName = $modelClass::tableName();
				$this->from = array($tableName);
			}
			/** @var $qb QueryBuilder */
			$qb = $db->getQueryBuilder();
Qiang Xue committed
244
			$this->sql = $qb->build($this);
Qiang Xue committed
245
		}
Qiang Xue committed
246
		return $db->createCommand($this->sql, $this->params);
Qiang Xue committed
247 248
	}

Qiang Xue committed
249 250 251 252 253
	/**
	 * Sets the [[asArray]] property.
	 * @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
	 * @return ActiveQuery the query object itself
	 */
Qiang Xue committed
254 255 256 257 258 259
	public function asArray($value = true)
	{
		$this->asArray = $value;
		return $this;
	}

Qiang Xue committed
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
	/**
	 * Specifies the relations with which this query should be performed.
	 *
	 * The parameters to this method can be either one or multiple strings, or a single array
	 * of relation names and the optional callbacks to customize the relations.
	 *
	 * The followings are some usage examples:
	 *
	 * ~~~
	 * // find customers together with their orders and country
	 * Customer::find()->with('orders', 'country')->all();
	 * // find customers together with their country and orders of status 1
	 * Customer::find()->with(array(
	 *     'orders' => function($query) {
	 *         $query->andWhere('status = 1');
	 *     },
	 *     'country',
	 * ))->all();
	 * ~~~
	 *
	 * @return ActiveQuery the query object itself
	 */
Qiang Xue committed
282 283 284 285 286 287 288 289 290 291
	public function with()
	{
		$this->with = func_get_args();
		if (isset($this->with[0]) && is_array($this->with[0])) {
			// the parameter is given as an array
			$this->with = $this->with[0];
		}
		return $this;
	}

Qiang Xue committed
292 293 294 295 296
	/**
	 * Sets the [[indexBy]] property.
	 * @param string $column the name of the column by which the query results should be indexed by.
	 * @return ActiveQuery the query object itself
	 */
Qiang Xue committed
297
	public function indexBy($column)
Qiang Xue committed
298
	{
Qiang Xue committed
299
		$this->indexBy = $column;
Qiang Xue committed
300 301 302
		return $this;
	}

Qiang Xue committed
303
	private function createModels($rows)
Qiang Xue committed
304 305 306
	{
		$models = array();
		if ($this->asArray) {
Qiang Xue committed
307
			if ($this->indexBy === null) {
Qiang Xue committed
308 309 310
				return $rows;
			}
			foreach ($rows as $row) {
Qiang Xue committed
311
				$models[$row[$this->indexBy]] = $row;
Qiang Xue committed
312 313 314 315
			}
		} else {
			/** @var $class ActiveRecord */
			$class = $this->modelClass;
Qiang Xue committed
316
			if ($this->indexBy === null) {
Qiang Xue committed
317 318 319 320 321 322
				foreach ($rows as $row) {
					$models[] = $class::create($row);
				}
			} else {
				foreach ($rows as $row) {
					$model = $class::create($row);
Qiang Xue committed
323
					$models[$model->{$this->indexBy}] = $model;
Qiang Xue committed
324 325 326 327 328
				}
			}
		}
		return $models;
	}
Qiang Xue committed
329

Qiang Xue committed
330
	private function populateRelations(&$models, $with)
Qiang Xue committed
331 332
	{
		$primaryModel = new $this->modelClass;
Qiang Xue committed
333 334
		$relations = $this->normalizeRelations($primaryModel, $with);
		foreach ($relations as $name => $relation) {
Qiang Xue committed
335 336 337 338
			if ($relation->asArray === null) {
				// inherit asArray from primary query
				$relation->asArray = $this->asArray;
			}
Qiang Xue committed
339
			$relation->findWith($name, $models);
Qiang Xue committed
340 341
		}
	}
Qiang Xue committed
342 343 344 345 346 347

	/**
	 * @param ActiveRecord $model
	 * @param array $with
	 * @return ActiveRelation[]
	 */
Qiang Xue committed
348
	private function normalizeRelations($model, $with)
Qiang Xue committed
349 350
	{
		$relations = array();
Qiang Xue committed
351
		foreach ($with as $name => $callback) {
Qiang Xue committed
352
			if (is_integer($name)) {
Qiang Xue committed
353 354
				$name = $callback;
				$callback = null;
Qiang Xue committed
355 356 357 358 359 360 361 362 363
			}
			if (($pos = strpos($name, '.')) !== false) {
				// with sub-relations
				$childName = substr($name, $pos + 1);
				$name = substr($name, 0, $pos);
			} else {
				$childName = null;
			}

Qiang Xue committed
364 365
			$t = strtolower($name);
			if (!isset($relations[$t])) {
366 367 368
				$relation = $model->getRelation($name);
				$relation->primaryModel = null;
				$relations[$t] = $relation;
Qiang Xue committed
369
			} else {
Qiang Xue committed
370
				$relation = $relations[$t];
Qiang Xue committed
371 372 373
			}

			if (isset($childName)) {
Qiang Xue committed
374 375 376
				$relation->with[$childName] = $callback;
			} elseif ($callback !== null) {
				call_user_func($callback, $relation);
Qiang Xue committed
377 378 379 380
			}
		}
		return $relations;
	}
Qiang Xue committed
381
}