ActiveRelation.php 2.24 KB
Newer Older
Carsten Brandt committed
1 2 3
<?php
/**
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
Carsten Brandt committed
5 6 7
 * @license http://www.yiiframework.com/license/
 */

8
namespace yii\redis;
9

10 11
use yii\db\ActiveRelationInterface;
use yii\db\ActiveRelationTrait;
12

Carsten Brandt committed
13
/**
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.
Carsten Brandt committed
24 25 26 27
 *
 * @author Carsten Brandt <mail@cebe.cc>
 * @since 2.0
 */
28
class ActiveRelation extends ActiveQuery implements ActiveRelationInterface
Carsten Brandt committed
29
{
30
	use ActiveRelationTrait;
Carsten Brandt committed
31

32
	/**
33 34 35 36 37 38
	 * Executes a script created by [[LuaScriptBuilder]]
	 * @param Connection $db the database connection used to execute the query.
	 * If this parameter is not given, the `db` application component will be used.
	 * @param string $type the type of the script to generate
	 * @param null $column
	 * @return array|bool|null|string
39
	 */
40
	protected function executeScript($db, $type, $column=null)
Carsten Brandt committed
41 42 43 44 45
	{
		if ($this->primaryModel !== null) {
			// lazy loading
			if ($this->via instanceof self) {
				// via pivot table
46
				$viaModels = $this->via->findPivotRows([$this->primaryModel]);
Carsten Brandt committed
47 48 49
				$this->filterByModels($viaModels);
			} elseif (is_array($this->via)) {
				// via relation
50
				/** @var ActiveRelation $viaQuery */
Carsten Brandt committed
51 52 53 54 55 56 57
				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);
58
					$viaModels = $model === null ? [] : [$model];
Carsten Brandt committed
59 60 61
				}
				$this->filterByModels($viaModels);
			} else {
62
				$this->filterByModels([$this->primaryModel]);
63 64
			}
		}
65
		return parent::executeScript($db, $type, $column);
Carsten Brandt committed
66
	}
Carsten Brandt committed
67
}