ActiveRelation.php 9.23 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 12
use yii\db\Connection;
use yii\db\Command;
Qiang Xue committed
13
use yii\base\InvalidConfigException;
Qiang Xue committed
14

Qiang Xue committed
15
/**
Qiang Xue committed
16 17 18 19 20 21 22 23 24 25
 * 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
26 27 28 29
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
Qiang Xue committed
30
class ActiveRelation extends ActiveQuery
Qiang Xue committed
31
{
Qiang Xue committed
32
	/**
Qiang Xue committed
33
	 * @var boolean whether this relation should populate all query results into AR instances.
Qiang Xue committed
34
	 * If false, only the first row of the results will be retrieved.
Qiang Xue committed
35
	 */
Qiang Xue committed
36
	public $multiple;
Qiang Xue committed
37 38 39 40
	/**
	 * @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
41
	public $primaryModel;
Qiang Xue committed
42 43 44
	/**
	 * @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
45 46
	 * must be the corresponding columns from the primary table.
	 * Do not prefix or quote the column names as they will be done automatically by Yii.
Qiang Xue committed
47
	 */
Qiang Xue committed
48
	public $link;
Qiang Xue committed
49
	/**
Qiang Xue committed
50 51
	 * @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
52
	 */
53
	public $via;
Qiang Xue committed
54

Qiang Xue committed
55
	/**
Qiang Xue committed
56 57
	 * 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
58
	 * @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
Qiang Xue committed
59 60
	 * Its signature should be `function($query)`, where `$query` is the query to be customized.
	 * @return ActiveRelation the relation object itself.
Qiang Xue committed
61
	 */
Qiang Xue committed
62
	public function via($relationName, $callable = null)
Qiang Xue committed
63
	{
64 65
		$relation = $this->primaryModel->getRelation($relationName);
		$this->via = array($relationName, $relation);
Qiang Xue committed
66 67
		if ($callable !== null) {
			call_user_func($callable, $relation);
Qiang Xue committed
68
		}
69
		return $this;
Qiang Xue committed
70 71
	}

Qiang Xue committed
72
	/**
Qiang Xue committed
73 74 75 76 77
	 * 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
78
	 * @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
Qiang Xue committed
79
	 * Its signature should be `function($query)`, where `$query` is the query to be customized.
Qiang Xue committed
80 81
	 * @return ActiveRelation
	 */
Qiang Xue committed
82
	public function viaTable($tableName, $link, $callable = null)
Qiang Xue committed
83
	{
Qiang Xue committed
84 85 86 87 88 89 90 91
		$relation = new ActiveRelation(array(
			'modelClass' => get_class($this->primaryModel),
			'from' => array($tableName),
			'link' => $link,
			'multiple' => true,
			'asArray' => true,
		));
		$this->via = $relation;
Qiang Xue committed
92 93
		if ($callable !== null) {
			call_user_func($callable, $relation);
Qiang Xue committed
94
		}
Qiang Xue committed
95 96
		return $this;
	}
Qiang Xue committed
97

Qiang Xue committed
98 99
	/**
	 * Creates a DB command that can be used to execute this query.
Qiang Xue committed
100 101
	 * @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
102 103
	 * @return Command the created DB command instance.
	 */
Qiang Xue committed
104
	public function createCommand($db = null)
Qiang Xue committed
105
	{
Qiang Xue committed
106
		if ($this->primaryModel !== null) {
Qiang Xue committed
107 108 109 110 111 112 113
			// 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
114 115 116
				/** @var $viaQuery ActiveRelation */
				list($viaName, $viaQuery) = $this->via;
				if ($viaQuery->multiple) {
Qiang Xue committed
117 118
					$viaModels = $viaQuery->all();
					$this->primaryModel->populateRelation($viaName, $viaModels);
Qiang Xue committed
119
				} else {
Qiang Xue committed
120 121
					$model = $viaQuery->one();
					$this->primaryModel->populateRelation($viaName, $model);
Qiang Xue committed
122
					$viaModels = $model === null ? array() : array($model);
Qiang Xue committed
123
				}
124 125 126 127
				$this->filterByModels($viaModels);
			} else {
				$this->filterByModels(array($this->primaryModel));
			}
Qiang Xue committed
128
		}
Qiang Xue committed
129
		return parent::createCommand($db);
Qiang Xue committed
130 131
	}

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

Qiang Xue committed
146 147 148 149 150 151 152 153 154 155
		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;
156
			$viaQuery->primaryModel = null;
Qiang Xue committed
157
			$viaModels = $viaQuery->findWith($viaName, $primaryModels);
158 159 160
			$this->filterByModels($viaModels);
		} else {
			$this->filterByModels($primaryModels);
Qiang Xue committed
161 162
		}

Qiang Xue committed
163
		if (count($primaryModels) === 1 && !$this->multiple) {
164
			$model = $this->one();
Qiang Xue committed
165
			foreach ($primaryModels as $i => $primaryModel) {
Qiang Xue committed
166 167 168 169 170
				if ($primaryModel instanceof ActiveRecord) {
					$primaryModel->populateRelation($name, $model);
				} else {
					$primaryModels[$i][$name] = $model;
				}
Qiang Xue committed
171
			}
172
			return array($model);
Qiang Xue committed
173 174
		} else {
			$models = $this->all();
175 176 177 178 179 180
			if (isset($viaModels, $viaQuery)) {
				$buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery->link);
			} else {
				$buckets = $this->buildBuckets($models, $this->link);
			}

Qiang Xue committed
181
			$link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link);
182
			foreach ($primaryModels as $i => $primaryModel) {
Qiang Xue committed
183
				$key = $this->getModelKey($primaryModel, $link);
Qiang Xue committed
184 185 186
				$value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? array() : null);
				if ($primaryModel instanceof ActiveRecord) {
					$primaryModel->populateRelation($name, $value);
187
				} else {
Qiang Xue committed
188
					$primaryModels[$i][$name] = $value;
189 190 191
				}
			}
			return $models;
Qiang Xue committed
192 193 194
		}
	}

Qiang Xue committed
195 196 197 198 199 200 201 202
	/**
	 * @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
203 204
	{
		$buckets = array();
Qiang Xue committed
205
		$linkKeys = array_keys($link);
Qiang Xue committed
206
		foreach ($models as $i => $model) {
Qiang Xue committed
207
			$key = $this->getModelKey($model, $linkKeys);
Qiang Xue committed
208
			if ($this->indexBy !== null) {
Qiang Xue committed
209 210 211
				$buckets[$key][$i] = $model;
			} else {
				$buckets[$key][] = $model;
Qiang Xue committed
212
			}
Qiang Xue committed
213
		}
214 215 216

		if ($viaModels !== null) {
			$viaBuckets = array();
Qiang Xue committed
217 218
			$viaLinkKeys = array_keys($viaLink);
			$linkValues = array_values($link);
219
			foreach ($viaModels as $viaModel) {
Qiang Xue committed
220 221
				$key1 = $this->getModelKey($viaModel, $viaLinkKeys);
				$key2 = $this->getModelKey($viaModel, $linkValues);
222 223
				if (isset($buckets[$key2])) {
					foreach ($buckets[$key2] as $i => $bucket) {
Qiang Xue committed
224
						if ($this->indexBy !== null) {
225 226 227 228 229 230 231 232 233 234
							$viaBuckets[$key1][$i] = $bucket;
						} else {
							$viaBuckets[$key1][] = $bucket;
						}
					}
				}
			}
			$buckets = $viaBuckets;
		}

Qiang Xue committed
235 236 237
		if (!$this->multiple) {
			foreach ($buckets as $i => $bucket) {
				$buckets[$i] = reset($bucket);
Qiang Xue committed
238
			}
Qiang Xue committed
239
		}
240
		return $buckets;
Qiang Xue committed
241 242
	}

Qiang Xue committed
243 244 245 246 247 248
	/**
	 * @param ActiveRecord|array $model
	 * @param array $attributes
	 * @return string
	 */
	private function getModelKey($model, $attributes)
Qiang Xue committed
249
	{
Qiang Xue committed
250
		if (count($attributes) > 1) {
Qiang Xue committed
251 252
			$key = array();
			foreach ($attributes as $attribute) {
Qiang Xue committed
253
				$key[] = $model[$attribute];
Qiang Xue committed
254 255 256
			}
			return serialize($key);
		} else {
Qiang Xue committed
257 258
			$attribute = reset($attributes);
			return $model[$attribute];
Qiang Xue committed
259 260 261
		}
	}

Qiang Xue committed
262 263 264 265
	/**
	 * @param array $models
	 */
	private function filterByModels($models)
Qiang Xue committed
266 267 268
	{
		$attributes = array_keys($this->link);
		$values = array();
Alexander Kochetov committed
269
		if (count($attributes) === 1) {
Qiang Xue committed
270 271 272 273 274 275
			// single key
			$attribute = reset($this->link);
			foreach ($models as $model) {
				$values[] = $model[$attribute];
			}
		} else {
Qiang Xue committed
276
			// composite keys
277
			foreach ($models as $model) {
Qiang Xue committed
278 279
				$v = array();
				foreach ($this->link as $attribute => $link) {
Qiang Xue committed
280
					$v[$attribute] = $model[$link];
Qiang Xue committed
281 282 283 284
				}
				$values[] = $v;
			}
		}
Qiang Xue committed
285
		$this->andWhere(array('in', $attributes, array_unique($values, SORT_REGULAR)));
Qiang Xue committed
286 287
	}

Qiang Xue committed
288 289 290 291
	/**
	 * @param ActiveRecord[] $primaryModels
	 * @return array
	 */
Qiang Xue committed
292
	private function findPivotRows($primaryModels)
Qiang Xue committed
293 294 295 296 297 298 299
	{
		if (empty($primaryModels)) {
			return array();
		}
		$this->filterByModels($primaryModels);
		/** @var $primaryModel ActiveRecord */
		$primaryModel = reset($primaryModels);
Qiang Xue committed
300
		$db = $primaryModel->getDb();
Qiang Xue committed
301 302 303
		$sql = $db->getQueryBuilder()->build($this);
		return $db->createCommand($sql, $this->params)->queryAll();
	}
Qiang Xue committed
304
}