Load HasOneOrMany keys.
@param Collection $relations
@param HasOneOrMany $relationClass
@param Model $relationModel
@param Model $model
@param Builder $query
@param $direction
162821
protected function loadHasOne(
        Collection $relations,
        HasOneOrMany $relationClass,
        Model $relationModel,
        Model $model,
        Builder $query,
        $direction
    ) {
        $this->loadHasOneOrMany($relations, $relationClass, $relationModel, $model, $query, $direction);
    }
1143515
public function load($names)
    {
        foreach ((array) $names as $name) {
            // 1. Load relation config
            $parts = explode('.', $name, 2);
            $name = $parts[0];
            $next = isset($parts[1]) ? $parts[1] : null;
            if (isset($this->loadedRelations[$name])) {
                continue;
            }

            /** @var BaseModel $related */
            $related = $this->$name();
            $isColl = $related->isColl();
            $serviceName = $this->getClassServiceName($related);
            $relation = $this->relations[$serviceName];

            // 2. Fetch relation record data
            $ids = $this->getAll($relation['localKey']);
            $ids = array_unique(array_filter($ids));
            if ($ids) {
                $this->relatedValue = $ids;
                $related = $this->$name();
                $this->relatedValue = null;
            } else {
                $related = null;
            }

            // 3. Load relation data
            if (isset($relation['junctionTable'])) {
                $records = $this->loadBelongsToMany($related, $relation, $name);
            } elseif ($isColl) {
                $records = $this->loadHasMany($related, $relation, $name);
            } else {
                $records = $this->loadHasOne($related, $relation, $name);
            }

            // 4. Load nested relations
            if ($next && $records) {
                $records->load($next);
            }

            $this->loadedRelations[$name] = true;
        }

        return $this;
    }
67385
private function _loadOrCreateRelationModel($data, $fks, $modelClass, $relationName)
    {

        /** @var BaseActiveRecord $relationModel */
        $relationModel = null;
        if (!empty($fks)) {
            $relationModel = $modelClass::findOne($fks);
        }
        if (!($relationModel instanceof BaseActiveRecord) && !empty($data)) {
            $relationModel = new $modelClass;
        }
        // If a custom scenario is set, apply it here to correctly be able to set the model attributes
        if (array_key_exists($relationName, $this->_relationsScenario)) {
            $relationModel->setScenario($this->_relationsScenario[$relationName]);
        }
        if (($relationModel instanceof BaseActiveRecord) && is_array($data)) {
            $relationModel->setAttributes($data);
            if ($relationModel->hasMethod('loadRelations')) {
                $relationModel->loadRelations($data);
            }

        }
        return $relationModel;
    }
529087
def _merge_wheres_to_has(self, has_query, relation):
        
        relation_query = relation.get_base_query()

        has_query.merge_wheres(relation_query.wheres, relation_query.get_bindings())

        self._query.merge_bindings(has_query.get_query())
586032
protected function loadRelation(array $models, $name, Closure $constraints)
    {
        $relation = $this->getRelation($name);

        $relation->addEagerConstraints($models);

        call_user_func($constraints, $relation);

        $models = $relation->initRelation($models, $name);

        $results = $relation->getEager();

        return $relation->match($models, $results, $name);
    }
382274
public static function findRelations($modelOne, $modelTwo, $keys): array
    {
        $keys = (array)$keys;
        if (!$relations = self::getRelations($modelOne, $modelTwo)) {
            throw new RelationNotFoundException("Relations between model `$modelOne` and `$modelTwo` is not defined");
        }

        /* @var Table $tableOneClass name */
        $tableOneClass = self::getModelClass($modelOne);

        /* @var string $tableOneName */
        $tableOneName = $tableOneClass::getInstance()->getName();

        /* @var Table $tableTwoClass name */
        $tableTwoClass = self::getModelClass($modelTwo);

        /* @var string $tableTwoName */
        $tableTwoName = $tableTwoClass::getInstance()->getName();

        /* @var Query\Select $tableTwoSelect */
        $tableTwoSelect = $tableTwoClass::getInstance()::select();

        // check many to many relation
        if (\is_int(\array_keys($relations)[0])) {
            // many to many relation over third table
            $modelThree = $relations[0];

            // relations between target table and third table
            $relations = self::getRelations($modelTwo, $modelThree);

            /* @var Table $tableThreeClass name */
            $tableThreeClass = self::getModelClass($modelThree);

            /* @var string $tableTwoName */
            $tableThreeName = $tableThreeClass::getInstance()->getName();

            // join it to query
            $tableTwoSelect->join(
                $tableTwoName,
                $tableThreeName,
                $tableThreeName,
                $tableTwoName . '.' . $relations[$modelTwo] . '=' . $tableThreeName . '.' . $relations[$modelThree]
            );

            // relations between source table and third table
            $relations = self::getRelations($modelOne, $modelThree);

            // join it to query
            $tableTwoSelect->join(
                $tableThreeName,
                $tableOneName,
                $tableOneName,
                $tableThreeName . '.' . $relations[$modelThree] . '=' . $tableOneName . '.' . $relations[$modelOne]
            );

            // set source keys
            $tableTwoSelect->where($tableOneName . '.' . $relations[$modelOne] . ' IN (?)', $keys);
        } else {
            // set source keys
            $tableTwoSelect->where($relations[$modelTwo] . ' IN (?)', $keys);
        }
        return $tableTwoSelect->execute();
    }
691130
public function load($relations)
    {
        if ($this->isNotEmpty()) {
            if (is_string($relations)) {
                $relations = func_get_args();
            }

            $query = $this->first()->newQueryWithoutRelationships()->with($relations);

            $this->items = $query->eagerLoadRelations($this->items);
        }

        return $this;
    }
560943
protected function safeWith(Builder $query, $relations)
	{
		if (is_string($relations)) {
			$relations = func_get_args();
			array_shift($relations);
		}

		// Loop through all relations to check for valid relationship signatures
		foreach ($relations as $name => $constraints) {
			// Constraints may be passed in either form:
			// 2 => 'relation.nested'
			// or
			// 'relation.nested' => function() { ... }
			$constraints_are_name = is_numeric($name);
			$relation_name = $constraints_are_name ? $constraints : $name;

			// If this relation is not includable, skip
			// We expect to see foo.nested.relation in includable if the 3 level nested relationship is includable
			if (! $this->isIncludable($relation_name)) {
				unset($relations[$name]);
				continue;
			}

			// Expand the dot-notation to see all relations
			$nested_relations = explode(self::GLUE, $relation_name);
			$model = $query->getModel();

			// Don't allow eager loads beyond the eager load depth
			$nested_relations = $this->applyDepthRestriction($nested_relations);

			// We want to apply the depth restricted relations to the original relations array
			$cleaned_relation = join(self::GLUE, $nested_relations);
			if ($cleaned_relation === '') {
				unset($relations[$name]);
			} elseif ($constraints_are_name) {
				$relations[$name] = $cleaned_relation;
			} else {
				$relations[$cleaned_relation] = $constraints;
				unset($relations[$name]);
			}

			foreach ($nested_relations as $index => $relation) {

				if ($this->isRelation($model, $relation, get_class($model))) {
					// Iterate through relations if they actually exist
					$model = $model->$relation()->getRelated();
				} elseif ($index > 0) {
					// If we found any valid relations, pass them through
					$safe_relation = implode(self::GLUE, array_slice($nested_relations, 0, $index));
					if ($constraints_are_name) {
						$relations[$name] = $safe_relation;
					} else {
						unset($relations[$name]);
						$relations[$safe_relation] = $constraints;
					}
				} else {
					// If we didn't, remove this relation specification
					unset($relations[$name]);
					break;
				}
			}
		}

		$query->with($relations);
	}
390805
public function edgeFromRelationWithDirection(Relationship $relation, Model $parent, Model $related, $direction)
    {
        // If the direction is of type 'any' we need to figure out the relationship direction
        // from the determined relation.
        if ($direction == 'any')
        {
            $direction = $this->directionFromRelation($relation, $parent, $related);
        }

        // Based on the direction we are now able to construct the edge class name and call for
        // an instance of it then pass it the actual relationship that was previously found.
        $class = $this->getEdgeClass($direction);
        $edge = new $class($this->query, $parent, $related, $relation->getType());
        $edge->setRelation($relation, true);

        return $edge;
    }
50624
public static function queryModelRelations($model, ...$names)
    {
        $relations = AnnotationManager::getPropertiesAnnotations(BeanFactory::getObjectClass($model), RelationBase::class);
        foreach($names as $name)
        {
            if(isset($relations[$name]))
            {
                Query::init($model, $name, $relations[$name][0], true);
            }
        }
    }
1057476
public function findRelation($entity, $relationName, $orderColumn = null, $orderType = null) {
        $this->load();
        $mapper = MapperBuilder::buildFromClassName($this->mapping, get_class($entity));
        $relation = $mapper->getRelation($relationName);
        $relationMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity());

        $selectQuery = "SELECT tmain.* FROM `" . $relationMapper->getTable() . "` tmain ";
        $joinQuery = QueryBuilder::buildJoinRelationQuery($relation, "tmain", "j1");
        $whereQuery = "WHERE j1." . $relation->getLocalColumn() . " = '" . $entity->getId() . "'";

        $orderQuery = "";
        if (!is_null($orderColumn)) {
            $orderQuery .= "ORDER BY $orderColumn ";
            if (!is_null($orderType)) {
                $orderQuery .= "$orderType";
            } else {
                $orderQuery .= "ASC";
            }
        }

        $query = $selectQuery . $joinQuery . $whereQuery . $orderQuery;
        $queryResult = $this->getDataSource()->query($query);
        if ($queryResult) {
            $collection = new Collection($relationMapper->getClass(), $queryResult, $relationMapper);
        } else {
            $collection = new Collection($relationMapper->getClass(), array(), $relationMapper);
        }

        return $collection;
    }
541504
private function getRelations(Repository $repository, array $relations = [])
    {
        // if we have relation array passed, ignore request input
        if (count($relations) === 0) {
            $relations = Input::get('with');

            if (!is_array($relations)) {
                $relations = $this->inputService->decode('with');
            }
        }

        $result = [];
        $repo_relations = $repository->relations();
        foreach ($relations as $key => $value) {
            if (in_array($key, $repo_relations)) {
                $result[] = $key;
            } elseif (in_array($value, $repo_relations)) {
                $result[] = $value;
            }
        }

        return $result;
    }
292046
public function constrainQuery(EloquentBuilder &$query, $relatedModel, $constraint)
	{
		//if the column hasn't been joined yet, join it
		if (!$this->validator->isJoined($query, $this->getOption('table')))
		{
			$query->join($this->getOption('table'), $relatedModel->getTable().'.'.$relatedModel->getKeyName(), '=', $this->getOption('column2'));
		}

		$query->where($this->getOption('table').'.'.$this->getOption('column'), '=', $constraint);
	}
117016
private function linkJunctionByKeys($relation, $keys, $removeKeys = null)
    {
        /** @var \yii\db\ActiveRecord $owner */
        $owner = $this->owner;
        if ($owner->getIsNewRecord()) {
            throw new InvalidCallException('Unable to link model: the model cannot be newly created.');
        }
        /* @var $viaRelation \yii\db\ActiveQuery */
        $viaRelation = is_array($relation->via) ? $relation->via[1] : $relation->via;
        if (is_array($relation->via)) {
            /* @var $viaClass \yii\db\ActiveRecord */
            $viaClass = $viaRelation->modelClass;
            $viaTable = $viaClass::getTableSchema()->fullName;
        } else {
            /* @var $viaTable string */
            $viaTable = reset($relation->via->from);
        }
        $schema = $owner::getDb()->getSchema();

        $this->checkAccess($relation->modelClass, array_merge($keys, $removeKeys === null ? [] : $removeKeys), 'read');

        if (!empty($keys) || !empty($removeKeys)) {
            $owner::getDb()->createCommand()
                ->delete(
                    $viaTable,
                    [
                        'and',
                        $removeKeys === null
                            ? $this->buildKeyInCondition('not in', array_values($relation->link), $keys)
                            : $this->buildKeyInCondition('in', array_values($relation->link), $removeKeys),
                        array_combine(
                            array_keys($viaRelation->link),
                            $owner->getAttributes(array_values($viaRelation->link))
                        ),
                    ]
                )->execute();
        }

        if (empty($keys)) {
            return;
        }

        /** @var \yii\db\ActiveRecord $relationClass */
        $relationClass = $relation->modelClass;
        $quotedViaTable = $schema->quoteTableName($viaTable);
        $quotedColumns = implode(', ', array_map(
            [$schema, 'quoteColumnName'],
            array_merge(
                array_keys($viaRelation->link),
                array_values($relation->link)
            )
        ));
        $prefixedPrimaryKeys = array_map(function ($c) {
            return 't.'.$c;
        }, array_keys($relation->link));
        $prefixedForeignKeys = array_map(function ($c) {
            return 'j.'.$c;
        }, array_values($relation->link));

        $alreadyLinked = $relation->select(array_keys($relation->link))->asArray()->all();
        // a subquery is used as a more SQL portable way to specify list of values by putting them in a condition
        $subquery = (new Query())
            ->select(array_merge(
                array_map(
                    function ($c) use ($schema) {
                        return '('.$schema->quoteValue($c).')';
                    },
                    $owner->getAttributes(array_values($viaRelation->link))
                ),
                $prefixedPrimaryKeys
            ))
            ->from($relationClass::tableName().' t')
            ->where($this->buildKeyInCondition('in', $prefixedPrimaryKeys, $keys))
            ->andWhere($this->buildKeyInCondition('not in', $prefixedPrimaryKeys, $alreadyLinked));
        if ($removeKeys === null) {
            $subquery->leftJoin($viaTable.' j', array_merge(
                array_combine(array_map(function ($c) {
                    return 'j.'.$c;
                }, array_keys($viaRelation->link)), $owner->getAttributes(array_values($viaRelation->link))),
                array_combine($prefixedForeignKeys, array_map(function ($k) {
                    return new Expression($k);
                }, $prefixedPrimaryKeys))
            ));
            $subquery->andWhere(array_fill_keys($prefixedForeignKeys, null));
        }
        list ($subquery, $params) = $owner::getDb()->getQueryBuilder()->build($subquery);
        $query = "INSERT INTO $quotedViaTable ($quotedColumns) $subquery";
        $owner::getDb()->createCommand($query, $params)->execute();
    }
1143708
public function hasMany($entity, string $related, string $foreignKey = null, string $localKey = null): HasMany
    {
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $localKey = $localKey ?: $this->getKeyName();

        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addManyRelation($relation);
        $this->addForeignRelation($relation);

        return new HasMany($relatedMapper, $entity, $foreignKey, $localKey);
    }
981004
protected function loadRelationOrder(Builder $query, $direction)
    {
        /** @var Relation $relationClass */
        $relations = collect(explode('.', $this->name));
        $loop = 0;
        if ($relations->count() >= 2) {
            $query->select($query->getModel()->getTable().'.*');

            do {
                $model = ! $loop++ ? $query->getModel() : $relationClass->getModel();
                $relation = $relations->shift();

                if (method_exists($model, $relation)) {
                    $relationClass = $model->{$relation}();
                    $relationModel = $relationClass->getRelated();

                    $loadRelationMethod = implode('', ['load', class_basename(get_class($relationClass))]);
                    call_user_func([$this, $loadRelationMethod],
                        $relations, $relationClass, $relationModel, $model, $query, $direction);
                } else {
                    break;
                }
            } while (true);

            if ($this->sortedColumnAlias) {
                $query->orderBy(DB::raw($this->sortedColumnAlias), $direction);
            }
        }
    }
382495
public function cascade($models, $direction, array $directionData = [])
    {
        try {
            $this->direction = $direction;
            $this->directionData = $directionData;
            $this->run($models);
            //All ok we commit all database queries
            foreach ($this->dbsToTransact as $connectionToTransact) {
                DB::connection($connectionToTransact)->commit();
            }
        } catch (\Exception $e) {
            //Rollback the transaction before throw exception
            foreach ($this->dbsToTransact as $connectionToTransact) {
                DB::connection($connectionToTransact)->rollBack();
            }

            throw new SoftCascadeLogicException($e->getMessage(), null, $e);
        }
    }