ActiveRelation.php 9.43 KB
Newer Older
Qiang Xue committed
1
<?php
Qiang Xue committed
2 3 4
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @link http://www.yiiframework.com/
Qiang Xue committed
5
 * @copyright Copyright (c) 2008 Yii Software LLC
Qiang Xue committed
6 7
 * @license http://www.yiiframework.com/license/
 */
Qiang Xue committed
8

Qiang Xue committed
9
namespace yii\db;
Qiang Xue committed
10

Qiang Xue committed
11
use yii\base\InvalidConfigException;
Qiang Xue committed
12

Qiang Xue committed
13
/**
Qiang Xue committed
14 15 16 17 18 19 20 21 22 23
 * ActiveRelation represents a relation between two Active Record classes.
 *
 * ActiveRelation instances are usually created by calling [[ActiveRecord::hasOne()]] and
 * [[ActiveRecord::hasMany()]]. An Active Record class declares a relation by defining
 * a getter method which calls one of the above methods and returns the created ActiveRelation object.
 *
 * A relation is specified by [[link]] which represents the association between columns
 * of different tables; and the multiplicity of the relation is indicated by [[multiple]].
 *
 * If a relation involves a pivot table, it may be specified by [[via()]] or [[viaTable()]] method.
Qiang Xue committed
24 25 26 27
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
28
class ActiveRelation extends ActiveQuery
Qiang Xue committed
29
{
Qiang Xue committed
30
	/**
Qiang Xue committed
31
	 * @var boolean whether this relation should populate all query results into AR instances.
Qiang Xue committed
32
	 * If false, only the first row of the results will be retrieved.
Qiang Xue committed
33
	 */
Qiang Xue committed
34
	public $multiple;
Qiang Xue committed
35 36 37 38
	/**
	 * @var ActiveRecord the primary model that this relation is associated with.
	 * This is used only in lazy loading with dynamic query options.
	 */
Qiang Xue committed
39
	public $primaryModel;
Qiang Xue committed
40 41 42
	/**
	 * @var array the columns of the primary and foreign tables that establish the relation.
	 * The array keys must be columns of the table for this relation, and the array values
Qiang Xue committed
43
	 * must be the corresponding columns from the primary table.
44
	 * Do not prefix or quote the column names as this will be done automatically by Yii.
Qiang Xue committed
45
	 */
Qiang Xue committed
46
	public $link;
Qiang Xue committed
47
	/**
Qiang Xue committed
48 49
	 * @var array|ActiveRelation the query associated with the pivot table. Please call [[via()]]
	 * or [[viaTable()]] to set this property instead of directly setting it.
Qiang Xue committed
50
	 */
51
	public $via;
Qiang Xue committed
52

53 54 55 56 57 58 59 60 61 62
	/**
	 * Clones internal objects.
	 */
	public function __clone()
	{
		if (is_object($this->via)) {
			// make a clone of "via" object so that the same query object can be reused multiple times
			$this->via = clone $this->via;
		}
	}
63

Qiang Xue committed
64
	/**
Qiang Xue committed
65 66
	 * Specifies the relation associated with the pivot table.
	 * @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
Qiang Xue committed
67
	 * @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
Qiang Xue committed
68 69
	 * Its signature should be `function($query)`, where `$query` is the query to be customized.
	 * @return ActiveRelation the relation object itself.
Qiang Xue committed
70
	 */
Qiang Xue committed
71
	public function via($relationName, $callable = null)
Qiang Xue committed
72
	{
73 74
		$relation = $this->primaryModel->getRelation($relationName);
		$this->via = array($relationName, $relation);
Qiang Xue committed
75 76
		if ($callable !== null) {
			call_user_func($callable, $relation);
Qiang Xue committed
77
		}
78
		return $this;
Qiang Xue committed
79 80
	}

Qiang Xue committed
81
	/**
Qiang Xue committed
82 83 84 85 86
	 * Specifies the pivot table.
	 * @param string $tableName the name of the pivot table.
	 * @param array $link the link between the pivot table and the table associated with [[primaryModel]].
	 * The keys of the array represent the columns in the pivot table, and the values represent the columns
	 * in the [[primaryModel]] table.
Qiang Xue committed
87
	 * @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
Qiang Xue committed
88
	 * Its signature should be `function($query)`, where `$query` is the query to be customized.
Qiang Xue committed
89 90
	 * @return ActiveRelation
	 */
Qiang Xue committed
91
	public function viaTable($tableName, $link, $callable = null)
Qiang Xue committed
92
	{
Qiang Xue committed
93 94 95 96 97 98 99 100
		$relation = new ActiveRelation(array(
			'modelClass' => get_class($this->primaryModel),
			'from' => array($tableName),
			'link' => $link,
			'multiple' => true,
			'asArray' => true,
		));
		$this->via = $relation;
Qiang Xue committed
101 102
		if ($callable !== null) {
			call_user_func($callable, $relation);
Qiang Xue committed
103
		}
Qiang Xue committed
104 105
		return $this;
	}
Qiang Xue committed
106

Qiang Xue committed
107 108
	/**
	 * Creates a DB command that can be used to execute this query.
Qiang Xue committed
109 110
	 * @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
111 112
	 * @return Command the created DB command instance.
	 */
Qiang Xue committed
113
	public function createCommand($db = null)
Qiang Xue committed
114
	{
Qiang Xue committed
115
		if ($this->primaryModel !== null) {
Qiang Xue committed
116 117 118 119 120 121 122
			// lazy loading
			if ($this->via instanceof self) {
				// via pivot table
				$viaModels = $this->via->findPivotRows(array($this->primaryModel));
				$this->filterByModels($viaModels);
			} elseif (is_array($this->via)) {
				// via relation
Qiang Xue committed
123 124 125
				/** @var $viaQuery ActiveRelation */
				list($viaName, $viaQuery) = $this->via;
				if ($viaQuery->multiple) {
Qiang Xue committed
126 127
					$viaModels = $viaQuery->all();
					$this->primaryModel->populateRelation($viaName, $viaModels);
Qiang Xue committed
128
				} else {
Qiang Xue committed
129 130
					$model = $viaQuery->one();
					$this->primaryModel->populateRelation($viaName, $model);
Qiang Xue committed
131
					$viaModels = $model === null ? array() : array($model);
Qiang Xue committed
132
				}
133 134 135 136
				$this->filterByModels($viaModels);
			} else {
				$this->filterByModels(array($this->primaryModel));
			}
Qiang Xue committed
137
		}
Qiang Xue committed
138
		return parent::createCommand($db);
Qiang Xue committed
139 140
	}

Qiang Xue committed
141 142
	/**
	 * Finds the related records and populates them into the primary models.
143
	 * This method is internally used by [[ActiveQuery]]. Do not call it directly.
Qiang Xue committed
144 145 146
	 * @param string $name the relation name
	 * @param array $primaryModels primary models
	 * @return array the related models
Qiang Xue committed
147
	 * @throws InvalidConfigException
Qiang Xue committed
148
	 */
Qiang Xue committed
149
	public function findWith($name, &$primaryModels)
Qiang Xue committed
150
	{
Qiang Xue committed
151
		if (!is_array($this->link)) {
Qiang Xue committed
152
			throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
Qiang Xue committed
153
		}
Qiang Xue committed
154

Qiang Xue committed
155 156 157 158 159 160 161 162 163 164
		if ($this->via instanceof self) {
			// via pivot table
			/** @var $viaQuery ActiveRelation */
			$viaQuery = $this->via;
			$viaModels = $viaQuery->findPivotRows($primaryModels);
			$this->filterByModels($viaModels);
		} elseif (is_array($this->via)) {
			// via relation
			/** @var $viaQuery ActiveRelation */
			list($viaName, $viaQuery) = $this->via;
165
			$viaQuery->primaryModel = null;
Qiang Xue committed
166
			$viaModels = $viaQuery->findWith($viaName, $primaryModels);
167 168 169
			$this->filterByModels($viaModels);
		} else {
			$this->filterByModels($primaryModels);
Qiang Xue committed
170 171
		}

Qiang Xue committed
172
		if (count($primaryModels) === 1 && !$this->multiple) {
173
			$model = $this->one();
Qiang Xue committed
174
			foreach ($primaryModels as $i => $primaryModel) {
Qiang Xue committed
175 176 177 178 179
				if ($primaryModel instanceof ActiveRecord) {
					$primaryModel->populateRelation($name, $model);
				} else {
					$primaryModels[$i][$name] = $model;
				}
Qiang Xue committed
180
			}
181
			return array($model);
Qiang Xue committed
182 183
		} else {
			$models = $this->all();
184 185 186 187 188 189
			if (isset($viaModels, $viaQuery)) {
				$buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery->link);
			} else {
				$buckets = $this->buildBuckets($models, $this->link);
			}

Qiang Xue committed
190
			$link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link);
191
			foreach ($primaryModels as $i => $primaryModel) {
Qiang Xue committed
192
				$key = $this->getModelKey($primaryModel, $link);
Qiang Xue committed
193 194 195
				$value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? array() : null);
				if ($primaryModel instanceof ActiveRecord) {
					$primaryModel->populateRelation($name, $value);
196
				} else {
Qiang Xue committed
197
					$primaryModels[$i][$name] = $value;
198 199 200
				}
			}
			return $models;
Qiang Xue committed
201 202 203
		}
	}

Qiang Xue committed
204 205 206 207 208 209 210 211
	/**
	 * @param array $models
	 * @param array $link
	 * @param array $viaModels
	 * @param array $viaLink
	 * @return array
	 */
	private function buildBuckets($models, $link, $viaModels = null, $viaLink = null)
Qiang Xue committed
212 213
	{
		$buckets = array();
Qiang Xue committed
214
		$linkKeys = array_keys($link);
Qiang Xue committed
215
		foreach ($models as $i => $model) {
Qiang Xue committed
216
			$key = $this->getModelKey($model, $linkKeys);
Qiang Xue committed
217
			if ($this->indexBy !== null) {
Qiang Xue committed
218 219 220
				$buckets[$key][$i] = $model;
			} else {
				$buckets[$key][] = $model;
Qiang Xue committed
221
			}
Qiang Xue committed
222
		}
223 224 225

		if ($viaModels !== null) {
			$viaBuckets = array();
Qiang Xue committed
226 227
			$viaLinkKeys = array_keys($viaLink);
			$linkValues = array_values($link);
228
			foreach ($viaModels as $viaModel) {
Qiang Xue committed
229 230
				$key1 = $this->getModelKey($viaModel, $viaLinkKeys);
				$key2 = $this->getModelKey($viaModel, $linkValues);
231 232
				if (isset($buckets[$key2])) {
					foreach ($buckets[$key2] as $i => $bucket) {
Qiang Xue committed
233
						if ($this->indexBy !== null) {
234 235 236 237 238 239 240 241 242 243
							$viaBuckets[$key1][$i] = $bucket;
						} else {
							$viaBuckets[$key1][] = $bucket;
						}
					}
				}
			}
			$buckets = $viaBuckets;
		}

Qiang Xue committed
244 245 246
		if (!$this->multiple) {
			foreach ($buckets as $i => $bucket) {
				$buckets[$i] = reset($bucket);
Qiang Xue committed
247
			}
Qiang Xue committed
248
		}
249
		return $buckets;
Qiang Xue committed
250 251
	}

Qiang Xue committed
252 253 254 255 256 257
	/**
	 * @param ActiveRecord|array $model
	 * @param array $attributes
	 * @return string
	 */
	private function getModelKey($model, $attributes)
Qiang Xue committed
258
	{
Qiang Xue committed
259
		if (count($attributes) > 1) {
Qiang Xue committed
260 261
			$key = array();
			foreach ($attributes as $attribute) {
Qiang Xue committed
262
				$key[] = $model[$attribute];
Qiang Xue committed
263 264 265
			}
			return serialize($key);
		} else {
Qiang Xue committed
266 267
			$attribute = reset($attributes);
			return $model[$attribute];
Qiang Xue committed
268 269 270
		}
	}

Qiang Xue committed
271 272 273 274
	/**
	 * @param array $models
	 */
	private function filterByModels($models)
Qiang Xue committed
275 276 277
	{
		$attributes = array_keys($this->link);
		$values = array();
Alexander Kochetov committed
278
		if (count($attributes) === 1) {
Qiang Xue committed
279 280 281 282 283 284
			// single key
			$attribute = reset($this->link);
			foreach ($models as $model) {
				$values[] = $model[$attribute];
			}
		} else {
Qiang Xue committed
285
			// composite keys
286
			foreach ($models as $model) {
Qiang Xue committed
287 288
				$v = array();
				foreach ($this->link as $attribute => $link) {
Qiang Xue committed
289
					$v[$attribute] = $model[$link];
Qiang Xue committed
290 291 292 293
				}
				$values[] = $v;
			}
		}
Qiang Xue committed
294
		$this->andWhere(array('in', $attributes, array_unique($values, SORT_REGULAR)));
Qiang Xue committed
295 296
	}

Qiang Xue committed
297 298 299 300
	/**
	 * @param ActiveRecord[] $primaryModels
	 * @return array
	 */
Qiang Xue committed
301
	private function findPivotRows($primaryModels)
Qiang Xue committed
302 303 304 305 306 307 308
	{
		if (empty($primaryModels)) {
			return array();
		}
		$this->filterByModels($primaryModels);
		/** @var $primaryModel ActiveRecord */
		$primaryModel = reset($primaryModels);
Qiang Xue committed
309
		$db = $primaryModel->getDb();
310 311
		list ($sql, $params) = $db->getQueryBuilder()->build($this);
		return $db->createCommand($sql, $params)->queryAll();
Qiang Xue committed
312
	}
Qiang Xue committed
313
}