Returns the value as a relation type from the model,
supports nesting via HTML array.
@return Relation
974136
protected function getRelationType()
    {
        list($model, $attribute) = $this->resolveModelAttribute($this->valueFrom);
        return $model->getRelationType($attribute);
    }
1313990
public function relationsToArray()
	{
		$attributes = array();

		foreach ($this->getArrayableRelations() as $key => $value)
		{
			if (in_array($key, $this->hidden)) continue;

			// If the values implements the Arrayable interface we can just call this
			// toArray method on the instances which will convert both models and
			// collections to their proper array form and we'll set the values.
			if ($value instanceof Arrayable)
			{
				$relation = $value->toArray();
			}

			// If the value is null, we'll still go ahead and set it in this list of
			// attributes since null is used to represent empty relationships if
			// if it a has one or belongs to type relationships on the models.
			elseif (is_null($value))
			{
				$relation = $value;
			}

			// If the relationships snake-casing is enabled, we will snake case this
			// key so that the relation attribute is snake cased in this returned
			// array to the developers, making this consistent with attributes.
			if (static::$snakeAttributes)
			{
				$key = snake_case($key);
			}

			// If the relation value has been set, we will set it on this attributes
			// list for returning. If it was not arrayable or null, we'll not set
			// the value on the array because it is some type of invalid value.
			if (isset($relation) || is_null($value))
			{
				$attributes[$key] = $relation;
			}

			unset($relation);
		}

		return $attributes;
	}
153838
protected function _getSecondRule() {
        $relation = $this->getRelation();
        $firstRule = $relation->name;
        $hasCustomRelName = $this->_hasCustomRelName();
        $modelIds = $this->_getModelIdsAlphabetically();

        if ($hasCustomRelName) {
            return $modelIds[0];
        }

        return $modelIds[0] !== $firstRule
            ? $modelIds[0]
            : $modelIds[1]
        ;
    }
1192057
public function getRelatedProperties()
    {
        //return $this->treeType->getCmsTreeTypeProperties();
        if (isset(self::$_treeTypes[$this->tree_type_id])) {
            $treeType = self::$_treeTypes[$this->tree_type_id];
        } else {
            self::$_treeTypes[$this->tree_type_id] = $this->treeType;
            $treeType = self::$_treeTypes[$this->tree_type_id];
        }
        if (!$treeType) {
            return CmsTreeTypeProperty::find()->where(['id' => null]);
        }
        //return $this->treeType->getCmsTreeTypeProperties();
        return $treeType->getCmsTreeTypeProperties();
    }
458772
final public function getRelations()
    {
        if ($this->relationsBuilt === false) {
            $tableMap = $this->getTableMap();
            $this->buildRelations($tableMap);
            $this->relationsBuilt = true;
        }

        return $this->relations;
    }
932667
public function getRelation() {
        if (is_null($this->_relation) || $this->_relation->getRelationId() !== $this->getRelationId()) {
            $model = $this->loader->getModels()->getRespondentRelationModel();
            $relationObject = $model->getRelation($this->getRespondentId(), $this->getRelationId());
            $this->_relation = $relationObject;
        }

        return $this->_relation;
    }
574804
protected function getRelations()
    {
        // Based on Barryvdh\LaravelIdeHelper\Console\ModelsCommand::getPropertiesFromMethods().
        return collect(get_class_methods($this->model))
            ->reject(function ($methodName) {
                return method_exists(Model::class, $methodName);
            })
            ->filter(function ($methodName) {
                $methodCode = $this->getMethodCode($methodName);

                return collect([
                    'belongsTo',
                    'morphTo',
                    'morphOne',
                    'morphMany',
                    'belongsToMany',
                    'morphedByMany',
                ])->contains(function ($relationName) use ($methodCode) {
                    return stripos($methodCode, "\$this->$relationName(");
                });
            })
            ->map(function ($methodName) {
                return $this->model->$methodName();
            })
            ->filter(function ($relation) {
                return $relation instanceof Relation;
            })
            ->all();
    }
916167
private function getRelationships()
    {
        $r = '';

        $relationships = (array)$this->xml->xpath('/draggy/relationships/relation');

        foreach ($relationships as $relation) {
            $relationAttributes = (array)$relation;
            $relationAttributes = $relationAttributes['@attributes'];

            $this->checkMandatoryAttributes('Relationship', $relationAttributes, ['from', 'to', 'type']);

            $r .= 'var l = new Link(\'' . str_replace(
                '\\',
                '\\\\',
                $relationAttributes['from']
            ) . '\',\'' . str_replace(
                '\\',
                '\\\\',
                $relationAttributes['to']
            ) . '\',\'' . $relationAttributes['type'] . '\',' . ( isset( $relationAttributes['fromAttribute'] ) ? '\'' . $relationAttributes['fromAttribute'] . '\'' : 'undefined' ) . ', ' . ( isset( $relationAttributes['toAttribute'] ) ? '\'' . $relationAttributes['toAttribute'] . '\'' : 'undefined' ) . ')' . PHP_EOL;

            if (isset( $relationAttributes['broken'] )) {
                $r .= 'l.setBroken(' . $relationAttributes['broken'] . ');' . PHP_EOL;
            }

            if (isset( $relationAttributes['persist'] )) {
                if ('true' === $relationAttributes['persist']) { // Backwards compatibility
                    $relationAttributes['persist'] = 'both';
                }

                $r .= 'l.setPersist("' . $relationAttributes['persist'] . '");' . PHP_EOL;
            } else { // Backwards compatibility
                $r .= 'l.setPersist(true);' . PHP_EOL;
            }

            if (isset( $relationAttributes['remove'] )) {
                if ('true' === $relationAttributes['remove']) { // Backwards compatibility
                    $relationAttributes['remove'] = 'both';
                }
                $r .= 'l.setRemove("' . $relationAttributes['remove'] . '");' . PHP_EOL;
            } else { // Backwards compatibility
                $r .= 'l.setRemove(true);' . PHP_EOL;
            }
        }

        return $r;
    }
268045
public function getRelation($relation)
    {
        $query = Relation::noConstraints(
            function () use ($relation){
                /** @var BaseModel $model */
                $model = $this->getModel();
                $relationType = $model->getReferencingType($relation);

                if (RelationSchema::HAS_ONE === $relationType) {
                    return $model->getHasOneByRelationName($relation);
                } elseif (RelationSchema::HAS_MANY === $relationType) {
                    return $model->getHasManyByRelationName($relation);
                } elseif (RelationSchema::MANY_MANY === $relationType) {
                    return $model->getBelongsToManyByRelationName($relation);
                } elseif (RelationSchema::BELONGS_TO === $relationType) {
                    return $model->getBelongsToByRelationName($relation);
                }

                return null;
            }
        );

        if (!empty($query)) {
            return $query;
        }

        if (!method_exists($this->getModel(), $relation)) {
            throw new BadRequestException('Unknown relationship: ' . $relation);
        }

        return parent::getRelation($relation);
    }
215169
private function getRelationValue($property) {
        $propertyName = $property;
        /** @var PersistableObject|PersistableObject[]|scalar|null $value */
        $value = &$this->$propertyName;                                 // existing property value

        if (is_object($value)) return $value;                           // relation is fetched and is an object or an array
        if (is_array ($value)) return $value;                           // (Collections are not yet implemented)

        $dao          =  $this->dao();
        $mapping      =  $dao->getMapping();
        $relation     = &$mapping['relations'][$propertyName];
        $isCollection = strEndsWith($relation['assoc'], 'many');
        /** @var PersistableObject[]|null $emptyResult */
        $emptyResult  = $isCollection ? [] : null;

        if ($value === null) {
            if (!$this->isPersistent())
                return $emptyResult;
        }
        else if ($value === false) {                                    // relation is fetched and marked as empty
            return $emptyResult;
        }

        // The relation is not yet fetched, the property is NULL or holds a physical foreign-key value.
        $type           = $relation['type'];                            // related class name
        /** @var DAO $relatedDao */
        $relatedDao     = $type::dao();
        $relatedMapping = $relatedDao->getMapping();
        $relatedTable   = $relatedMapping['table'];

        if ($value === null) {
            if (isset($relation['column'])) {                           // a local column with a foreign-key value of NULL
                $value = false;
                return $emptyResult;                                    // the relation is marked as empty
            }

            // a local key is used
            if (!isset($relation['key']))
                $relation['key'] = $mapping['identity']['name'];        // default local key is identity
            $keyName = $relation['key'];                                // the used local key property
            if ($this->$keyName === null) {
                $value = false;                                         // the relation is marked as empty
                return $emptyResult;
            }
            $keyColumn = $mapping['properties'][$keyName]['column'];    // the used local key column
            $refColumn = $relation['ref-column'];                       // the referencing column

            if (!isset($relation['join-table'])) {
                // the referencing column is part of the related table
                $refColumnType = $relatedMapping['columns'][$refColumn]['type'];
                $refValue      = $relatedDao->escapeLiteral($this->getPhysicalValue($keyColumn, $refColumnType));
                $sql = 'select r.*
                            from '.$relatedTable.' r
                            where r.'.$refColumn.' = '.$refValue;
            }
            else {
                // the referenced column is part of a join table
                $joinTable = $relation['join-table'];
                $keyValue  = $dao->escapeLiteral($this->getPhysicalValue($keyColumn));  // the physical local key value

                if (!isset($relation['foreign-key']))
                    $relation['foreign-key'] = $relatedMapping['identity']['name'];     // default foreign-key is identity
                $fkName      = $relation['foreign-key'];                                // the used foreign-key property
                $fkColumn    = $relatedMapping['properties'][$fkName]['column'];        // the used foreign-key column
                $fkRefColumn = $relation['fk-ref-column'];                              // join column referencing the foreign-key
                $sql = 'select r.*
                            from '.$relatedTable.' r
                            join '.$joinTable.'    j on r.'.$fkColumn.' = j.'.$fkRefColumn.'
                            where j.'.$refColumn.' = '.$keyValue;
            }
            if ($isCollection) {                                                        // default result sorting
                $relatedIdColumn = $relatedMapping['identity']['column'];               // the related identity column
                $sql .= ' order by r.'.$relatedIdColumn;                                // sort by identity
            }
        }
        else {
            // $value holds a non-NULL column-type foreign-key value pointing to a single related record
            if (isset($relation['join-table'])) {
                if (!isset($relation['foreign-key']))
                    $relation['foreign-key'] = $relatedMapping['identity']['name'];     // default foreign-key is identity
                $fkName   = $relation['foreign-key'];                                   // the used foreign-key property
                $fkColumn = $relatedMapping['properties'][$fkName]['column'];           // the used foreign-key column
            }
            else if (isset($relation['column'])) {                      // a local column referencing the foreign key
                if (!isset($relation['ref-column']))                    // default foreign-key is identity
                    $relation['ref-column'] = $relatedMapping['identity']['column'];
                $fkColumn = $relation['ref-column'];                    // the used foreign-key column
            }
            else {
                $fkColumn = $relatedMapping['identity']['column'];      // the used foreign-key column is identity
            }
            $fkValue = $relatedDao->escapeLiteral($value);
            $sql = 'select r.*
                        from '.$relatedTable.' r
                        where r.'.$fkColumn.' = '.$fkValue;
        }

        if (!$isCollection) $value = $relatedDao->find($sql);           // => PersistableObject
        else                $value = $relatedDao->findAll($sql);        // => PersistableObject[]

        return $value;
    }
960117
protected static function _relations($type = null, $name = null) {
		$self = static::_object();

		if ($name) {
			if (isset($self->_relationsToLoad[$name])) {
				$t = $self->_relationsToLoad[$name];
				unset($self->_relationsToLoad[$name]);
				return static::bind($t, $name, (array) $self->{$t}[$name]);
			}
			return isset($self->_relations[$name]) ? $self->_relations[$name] : null;
		}
		if (!$type) {
			foreach ($self->_relationsToLoad as $name => $t) {
				static::bind($t, $name, (array) $self->{$t}[$name]);
			}
			$self->_relationsToLoad = [];
			return $self->_relations;
		}
		foreach ($self->_relationsToLoad as $name => $t) {
			if ($type === $t) {
				static::bind($t, $name, (array) $self->{$t}[$name]);
				unset($self->_relationsToLoad[$name]);
			}
		}
		return array_filter($self->_relations, function($i) use ($type) {
			return $i->data('type') === $type;
		});
	}
1250417
public function getRelationshipsAsArray()
    {
        $relationships = $this->getRelationships();

        $relationships = $this->convertRelationshipsToArray($relationships);

        return $this->mergeRelationships($relationships);
    }
1091179
public static function related_class($relation)
	{
		$class = get_called_class();

		foreach (static::$_valid_relations as $rel_name => $rel_class)
		{
			if (property_exists($class, '_'.$rel_name))
			{
				if (isset(static::${'_'.$rel_name}[$relation]))
				{
					return static::${'_'.$rel_name}[$relation]['model_to'];
				}
			}
		}

		return null;
	}
487092
public function mapRelatives()
    {
        $relations = collect($this->relations());

        if ($relations->isEmpty()) {
            return false;
        }

        return $this->items = collect($this->all())
            ->map(function ($value, $key) use ($relations) {
                if ($relations->has($key)) {
                    $className = $relations->get($key);

                    return new $className($value);
                }

                return $value;
            })
            ->all();
    }
347259
private function getRelatedModel()
    {
        $idSuffix = '_id';

        return substr($this->key, 0, strlen($this->key) - strlen($idSuffix));
    }
1099096
public static function relations($type = null) {
		$self = static::_object();

		if ($type === null) {
			return static::_relations();
		}
		if (isset($self->_relationFieldNames[$type])) {
			$type = $self->_relationFieldNames[$type];
		}

		if (isset($self->_relations[$type])) {
			return $self->_relations[$type];
		}
		if (isset($self->_relationsToLoad[$type])) {
			return static::_relations(null, $type);
		}
		if (in_array($type, $self->_relationTypes, true)) {
			return array_keys(static::_relations($type));
		}
	}
1224114
protected function guessRelation()
    {
        if ($this->relation) {
            return $this->relation;
        }

        return Str::camel(str_replace('_id', '', $this->name));
    }