ActiveRelation.php 9.19 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 44
	 * 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
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

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

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

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

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

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

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

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

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

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

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

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

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

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