ActiveRelation.php 9.26 KB
Newer Older
Qiang Xue committed
1
<?php
Qiang Xue committed
2 3 4 5 6
/**
 * ActiveRelation class file.
 *
 * @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
 * @license http://www.yiiframework.com/license/
 */
Qiang Xue committed
10

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

Qiang Xue committed
13 14
use yii\db\Connection;
use yii\db\Command;
Qiang Xue committed
15
use yii\base\InvalidConfigException;
Qiang Xue committed
16

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

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

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

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

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

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

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

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

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

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

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

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

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

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