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

8
namespace yii\db;
9
use yii\base\InvalidCallException;
10 11

/**
12
 * ActiveQueryTrait implements the common methods and properties for active record query classes.
13 14 15 16 17
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
18
trait ActiveQueryTrait
19 20 21 22 23 24
{
	/**
	 * @var string the name of the ActiveRecord class.
	 */
	public $modelClass;
	/**
25
	 * @var array a list of relations that this query should be performed with
26 27 28 29 30 31 32 33 34 35 36 37 38
	 */
	public $with;
	/**
	 * @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;


	/**
	 * 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.
39
	 *
40 41
	 * @param string $name the method name to be called
	 * @param array $params the parameters passed to the method
42
	 * @throws \yii\base\InvalidCallException
43 44 45 46 47
	 * @return mixed the method return result
	 */
	public function __call($name, $params)
	{
		if (method_exists($this->modelClass, $name)) {
48 49 50 51
			$method = new \ReflectionMethod($this->modelClass, $name);
			if (!$method->isStatic() || !$method->isPublic()) {
				throw new InvalidCallException("The scope method \"{$this->modelClass}::$name()\" must be public and static.");
			}
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
			array_unshift($params, $this);
			call_user_func_array([$this->modelClass, $name], $params);
			return $this;
		} else {
			return parent::__call($name, $params);
		}
	}

	/**
	 * Sets the [[asArray]] property.
	 * @param boolean $value whether to return the query results in terms of arrays instead of Active Records.
	 * @return static the query object itself
	 */
	public function asArray($value = true)
	{
		$this->asArray = $value;
		return $this;
	}

	/**
	 * 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.
	 *
77 78 79 80 81
	 * A relation name can refer to a relation defined in [[modelClass]]
	 * or a sub-relation that stands for a relation of a related record.
	 * For example, `orders.address` means the `address` relation defined
	 * in the model class corresponding to the `orders` relation.
	 *
82 83 84 85 86
	 * The followings are some usage examples:
	 *
	 * ~~~
	 * // find customers together with their orders and country
	 * Customer::find()->with('orders', 'country')->all();
87 88
	 * // find customers together with their orders and the orders' shipping address
	 * Customer::find()->with('orders.address')->all();
89 90 91 92 93 94 95 96 97
	 * // find customers together with their country and orders of status 1
	 * Customer::find()->with([
	 *     'orders' => function($query) {
	 *         $query->andWhere('status = 1');
	 *     },
	 *     'country',
	 * ])->all();
	 * ~~~
	 *
Qiang Xue committed
98 99 100 101 102 103 104 105
	 * You can call `with()` multiple times. Each call will add relations to the existing ones.
	 * For example, the following two statements are equivalent:
	 *
	 * ~~~
	 * Customer::find()->with('orders', 'country')->all();
	 * Customer::find()->with('orders')->with('country')->all();
	 * ~~~
	 *
106 107 108 109
	 * @return static the query object itself
	 */
	public function with()
	{
Qiang Xue committed
110 111
		$with = func_get_args();
		if (isset($with[0]) && is_array($with[0])) {
112
			// the parameter is given as an array
Qiang Xue committed
113
			$with = $with[0];
114
		}
Qiang Xue committed
115 116 117 118 119 120 121 122 123 124 125 126 127 128

		if (empty($this->with)) {
			$this->with = $with;
		} elseif (!empty($with)) {
			foreach ($with as $name => $value) {
				if (is_integer($name)) {
					// repeating relation is fine as normalizeRelations() handle it well
					$this->with[] = $value;
				} else {
					$this->with[$name] = $value;
				}
			}
		}

129 130 131
		return $this;
	}

132 133 134 135 136
	/**
	 * Converts found rows into model instances
	 * @param array $rows
	 * @return array|ActiveRecord[]
	 */
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
	private function createModels($rows)
	{
		$models = [];
		if ($this->asArray) {
			if ($this->indexBy === null) {
				return $rows;
			}
			foreach ($rows as $row) {
				if (is_string($this->indexBy)) {
					$key = $row[$this->indexBy];
				} else {
					$key = call_user_func($this->indexBy, $row);
				}
				$models[$key] = $row;
			}
		} else {
153
			/** @var ActiveRecord $class */
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
			$class = $this->modelClass;
			if ($this->indexBy === null) {
				foreach ($rows as $row) {
					$models[] = $class::create($row);
				}
			} else {
				foreach ($rows as $row) {
					$model = $class::create($row);
					if (is_string($this->indexBy)) {
						$key = $model->{$this->indexBy};
					} else {
						$key = call_user_func($this->indexBy, $model);
					}
					$models[$key] = $model;
				}
			}
		}
		return $models;
	}

174
	/**
175 176 177
	 * Finds records corresponding to one or multiple relations and populates them into the primary models.
	 * @param array $with a list of relations that this query should be performed with. Please
	 * refer to [[with()]] for details about specifying this parameter.
178
	 * @param array $models the primary models (can be either AR instances or arrays)
179
	 */
180
	public function findWith($with, &$models)
181 182 183 184 185 186 187 188
	{
		$primaryModel = new $this->modelClass;
		$relations = $this->normalizeRelations($primaryModel, $with);
		foreach ($relations as $name => $relation) {
			if ($relation->asArray === null) {
				// inherit asArray from primary query
				$relation->asArray = $this->asArray;
			}
189
			$relation->populateRelation($name, $models);
190 191 192 193 194 195
		}
	}

	/**
	 * @param ActiveRecord $model
	 * @param array $with
196
	 * @return ActiveRelationInterface[]
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	 */
	private function normalizeRelations($model, $with)
	{
		$relations = [];
		foreach ($with as $name => $callback) {
			if (is_integer($name)) {
				$name = $callback;
				$callback = null;
			}
			if (($pos = strpos($name, '.')) !== false) {
				// with sub-relations
				$childName = substr($name, $pos + 1);
				$name = substr($name, 0, $pos);
			} else {
				$childName = null;
			}

214
			if (!isset($relations[$name])) {
215 216
				$relation = $model->getRelation($name);
				$relation->primaryModel = null;
217
				$relations[$name] = $relation;
218
			} else {
219
				$relation = $relations[$name];
220 221 222 223 224 225 226 227 228 229 230
			}

			if (isset($childName)) {
				$relation->with[$childName] = $callback;
			} elseif ($callback !== null) {
				call_user_func($callback, $relation);
			}
		}
		return $relations;
	}
}