You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

318 lines
9.5 KiB

13 years ago
<?php
13 years ago
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
13 years ago
* @license http://www.yiiframework.com/license/
*/
13 years ago
namespace yii\db;
13 years ago
use yii\base\InvalidConfigException;
12 years ago
13 years ago
/**
12 years ago
* 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.
13 years ago
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
12 years ago
class ActiveRelation extends ActiveQuery
13 years ago
{
13 years ago
/**
12 years ago
* @var boolean whether this relation should populate all query results into AR instances.
12 years ago
* If false, only the first row of the results will be retrieved.
13 years ago
*/
12 years ago
public $multiple;
13 years ago
/**
12 years ago
* @var ActiveRecord the primary model that this relation is associated with.
* This is used only in lazy loading with dynamic query options.
*/
12 years ago
public $primaryModel;
12 years ago
/**
13 years ago
* @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
12 years ago
* 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.
13 years ago
*/
12 years ago
public $link;
13 years ago
/**
12 years ago
* @var array|ActiveRelation the query associated with the pivot table. Please call [[via()]]
* or [[viaTable()]] to set this property instead of directly setting it.
13 years ago
*/
public $via;
12 years ago
/**
* Clones internal objects.
*/
public function __clone()
{
// make a clone of "via" object so that the same query object can be reused multiple times
if (is_object($this->via)) {
$this->via = clone $this->via;
} elseif (is_array($this->via)) {
$this->via = [$this->via[0], clone $this->via[1]];
}
}
12 years ago
/**
12 years ago
* Specifies the relation associated with the pivot table.
* @param string $relationName the relation name. This refers to a relation declared in [[primaryModel]].
* @param callable $callable a PHP callback for customizing the relation associated with the pivot table.
12 years ago
* Its signature should be `function($query)`, where `$query` is the query to be customized.
* @return static the relation object itself.
12 years ago
*/
public function via($relationName, $callable = null)
12 years ago
{
$relation = $this->primaryModel->getRelation($relationName);
$this->via = [$relationName, $relation];
if ($callable !== null) {
call_user_func($callable, $relation);
12 years ago
}
return $this;
12 years ago
}
12 years ago
/**
12 years ago
* 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 callable $callable a PHP callback for customizing the relation associated with the pivot table.
12 years ago
* Its signature should be `function($query)`, where `$query` is the query to be customized.
* @return static
12 years ago
*/
public function viaTable($tableName, $link, $callable = null)
12 years ago
{
$relation = new ActiveRelation([
12 years ago
'modelClass' => get_class($this->primaryModel),
'from' => [$tableName],
12 years ago
'link' => $link,
'multiple' => true,
'asArray' => true,
]);
12 years ago
$this->via = $relation;
if ($callable !== null) {
call_user_func($callable, $relation);
12 years ago
}
12 years ago
return $this;
}
12 years ago
12 years ago
/**
* Creates a DB command that can be used to execute this query.
12 years ago
* @param Connection $db the DB connection used to create the DB command.
* If null, the DB connection returned by [[modelClass]] will be used.
12 years ago
* @return Command the created DB command instance.
*/
12 years ago
public function createCommand($db = null)
12 years ago
{
12 years ago
if ($this->primaryModel !== null) {
12 years ago
// lazy loading
if ($this->via instanceof self) {
// via pivot table
$viaModels = $this->via->findPivotRows([$this->primaryModel]);
12 years ago
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/** @var ActiveRelation $viaQuery */
list($viaName, $viaQuery) = $this->via;
if ($viaQuery->multiple) {
$viaModels = $viaQuery->all();
$this->primaryModel->populateRelation($viaName, $viaModels);
} else {
$model = $viaQuery->one();
$this->primaryModel->populateRelation($viaName, $model);
$viaModels = $model === null ? [] : [$model];
12 years ago
}
$this->filterByModels($viaModels);
} else {
$this->filterByModels([$this->primaryModel]);
}
12 years ago
}
12 years ago
return parent::createCommand($db);
12 years ago
}
12 years ago
/**
* Finds the related records and populates them into the primary models.
* This method is internally used by [[ActiveQuery]]. Do not call it directly.
12 years ago
* @param string $name the relation name
* @param array $primaryModels primary models
* @return array the related models
* @throws InvalidConfigException
12 years ago
*/
12 years ago
public function findWith($name, &$primaryModels)
12 years ago
{
12 years ago
if (!is_array($this->link)) {
throw new InvalidConfigException('Invalid link: it must be an array of key-value pairs.');
12 years ago
}
12 years ago
12 years ago
if ($this->via instanceof self) {
// via pivot table
/** @var ActiveRelation $viaQuery */
12 years ago
$viaQuery = $this->via;
$viaModels = $viaQuery->findPivotRows($primaryModels);
$this->filterByModels($viaModels);
} elseif (is_array($this->via)) {
// via relation
/** @var ActiveRelation $viaQuery */
12 years ago
list($viaName, $viaQuery) = $this->via;
$viaQuery->primaryModel = null;
12 years ago
$viaModels = $viaQuery->findWith($viaName, $primaryModels);
$this->filterByModels($viaModels);
} else {
$this->filterByModels($primaryModels);
12 years ago
}
12 years ago
if (count($primaryModels) === 1 && !$this->multiple) {
$model = $this->one();
12 years ago
foreach ($primaryModels as $i => $primaryModel) {
if ($primaryModel instanceof ActiveRecord) {
$primaryModel->populateRelation($name, $model);
} else {
$primaryModels[$i][$name] = $model;
}
12 years ago
}
return [$model];
12 years ago
} else {
$models = $this->all();
if (isset($viaModels, $viaQuery)) {
$buckets = $this->buildBuckets($models, $this->link, $viaModels, $viaQuery->link);
} else {
$buckets = $this->buildBuckets($models, $this->link);
}
12 years ago
$link = array_values(isset($viaQuery) ? $viaQuery->link : $this->link);
foreach ($primaryModels as $i => $primaryModel) {
12 years ago
$key = $this->getModelKey($primaryModel, $link);
$value = isset($buckets[$key]) ? $buckets[$key] : ($this->multiple ? [] : null);
if ($primaryModel instanceof ActiveRecord) {
$primaryModel->populateRelation($name, $value);
} else {
$primaryModels[$i][$name] = $value;
}
}
return $models;
12 years ago
}
}
12 years ago
/**
* @param array $models
* @param array $link
* @param array $viaModels
* @param array $viaLink
* @return array
*/
private function buildBuckets($models, $link, $viaModels = null, $viaLink = null)
12 years ago
{
$buckets = [];
12 years ago
$linkKeys = array_keys($link);
12 years ago
foreach ($models as $i => $model) {
12 years ago
$key = $this->getModelKey($model, $linkKeys);
12 years ago
if ($this->indexBy !== null) {
12 years ago
$buckets[$key][$i] = $model;
} else {
$buckets[$key][] = $model;
12 years ago
}
12 years ago
}
if ($viaModels !== null) {
$viaBuckets = [];
12 years ago
$viaLinkKeys = array_keys($viaLink);
$linkValues = array_values($link);
foreach ($viaModels as $viaModel) {
12 years ago
$key1 = $this->getModelKey($viaModel, $viaLinkKeys);
$key2 = $this->getModelKey($viaModel, $linkValues);
if (isset($buckets[$key2])) {
foreach ($buckets[$key2] as $i => $bucket) {
12 years ago
if ($this->indexBy !== null) {
$viaBuckets[$key1][$i] = $bucket;
} else {
$viaBuckets[$key1][] = $bucket;
}
}
}
}
$buckets = $viaBuckets;
}
12 years ago
if (!$this->multiple) {
foreach ($buckets as $i => $bucket) {
$buckets[$i] = reset($bucket);
12 years ago
}
12 years ago
}
return $buckets;
12 years ago
}
12 years ago
/**
* @param ActiveRecord|array $model
* @param array $attributes
* @return string
*/
private function getModelKey($model, $attributes)
12 years ago
{
12 years ago
if (count($attributes) > 1) {
$key = [];
12 years ago
foreach ($attributes as $attribute) {
12 years ago
$key[] = $model[$attribute];
12 years ago
}
return serialize($key);
} else {
12 years ago
$attribute = reset($attributes);
return $model[$attribute];
12 years ago
}
}
12 years ago
/**
* @param array $models
*/
private function filterByModels($models)
12 years ago
{
$attributes = array_keys($this->link);
$values = [];
12 years ago
if (count($attributes) === 1) {
12 years ago
// single key
$attribute = reset($this->link);
foreach ($models as $model) {
if (($value = $model[$attribute]) !== null) {
$values[] = $value;
}
12 years ago
}
} else {
12 years ago
// composite keys
foreach ($models as $model) {
$v = [];
12 years ago
foreach ($this->link as $attribute => $link) {
12 years ago
$v[$attribute] = $model[$link];
12 years ago
}
$values[] = $v;
}
}
$this->andWhere(['in', $attributes, array_unique($values, SORT_REGULAR)]);
12 years ago
}
12 years ago
/**
* @param ActiveRecord[] $primaryModels
* @return array
*/
12 years ago
private function findPivotRows($primaryModels)
12 years ago
{
if (empty($primaryModels)) {
return [];
12 years ago
}
$this->filterByModels($primaryModels);
/** @var ActiveRecord $primaryModel */
12 years ago
$primaryModel = reset($primaryModels);
12 years ago
$db = $primaryModel->getDb();
list ($sql, $params) = $db->getQueryBuilder()->build($this);
return $db->createCommand($sql, $params)->queryAll();
12 years ago
}
13 years ago
}