@param $db_type
@param GeneratorFieldRelation|null $relation

@return string
508379
private function getPHPDocType($db_type, $relation = null)
    {
        switch ($db_type) {
            case 'datetime':
                return 'string|\Carbon\Carbon';
            case '1t1':
                return '\\'.$this->commandData->config->nsModel.'\\'.$relation->inputs[0].' '.camel_case($relation->inputs[0]);
            case 'mt1':
                if (isset($relation->inputs[1])) {
                    $relationName = str_replace('_id', '', strtolower($relation->inputs[1]));
                } else {
                    $relationName = $relation->inputs[0];
                }

                return '\\'.$this->commandData->config->nsModel.'\\'.$relation->inputs[0].' '.camel_case($relationName);
            case '1tm':
            case 'mtm':
            case 'hmt':
                return '\Illuminate\Database\Eloquent\Collection'.' '.camel_case(str_plural($relation->inputs[0]));
            default:
                $fieldData = SwaggerGenerator::getFieldType($db_type);
                if (!empty($fieldData['fieldType'])) {
                    return $fieldData['fieldType'];
                }

                return $db_type;
        }
    }
1190306
public function generateForeignItemsQuery(Saveable $class, $relation_details)
        {
            $query = $this->getQuery();
            $foreign_table = $class->getB2DBTable();
            $foreign_table_class = '\\'.get_class($foreign_table);
            $item_class = (array_key_exists('class', $relation_details)) ? $relation_details['class'] : null;
            $item_column = null;
            $item_table_class = null;
            if ($relation_details['manytomany']) {
                $item_table_class = Core::getCachedB2DBTableClass($item_class);
            }
            if ($relation_details['foreign_column']) {
                $saveable_class = '\\'.get_class($class);
                $table_details = ($item_class) ? Core::getCachedTableDetails($item_class) : Core::getTableDetails($relation_details['joinclass']);
                if ($relation_details['orderby']) {
                    $query->addOrderBy("{$table_details['name']}." . $relation_details['orderby']);
                }
                $query->where("{$table_details['name']}." . $relation_details['foreign_column'], $class->getB2DBSaveablePropertyValue(Core::getCachedColumnPropertyName($saveable_class, $foreign_table->getIdColumn())));
                if (array_key_exists('discriminator', $table_details) && $table_details['discriminator'] && array_key_exists($saveable_class, $table_details['discriminator']['discriminators'])) {
                    $query->where($table_details['discriminator']['column'], $table_details['discriminator']['discriminators'][$saveable_class]);
                }
            } else {
                foreach ($this->getForeignColumns() as $column => $details) {
                    if ($details['class'] == $foreign_table_class) {
                        $foreign_column = ($details['key']) ? $details['key'] : $foreign_table->getIdColumn();
                        $property_name = Core::getCachedColumnPropertyName(Core::getCachedTableEntityClass($details['class']), $foreign_column);
                        $value = $class->getB2DBSaveablePropertyValue($property_name);
                        $query->where($column, $value);
                    } elseif ($item_class && $details['class'] == $item_table_class) {
                        $item_column = $column;
                    }
                }
                if ($relation_details['orderby']) {
                    $query->addOrderBy($foreign_table->getB2DBName() . "." . $relation_details['orderby']);
                }
            }
            return array($query, $item_class, $item_column);
        }
340023
public function join(
        $foreign_table,
        $master_field = null,
        $join_kind = null,
        $_foreign_alias = null,
        $relation = null
    ) {
        if (!$_foreign_alias) {
            $_foreign_alias = '_'.$foreign_table[0];
        }
        $_foreign_alias = $this->_unique($this->relations, $_foreign_alias);

        /** @type SQL_Relation $rel */
        $rel = $this->add('SQL_Relation', $_foreign_alias);

        return $this->relations[$_foreign_alias] = $rel
            ->set($foreign_table, $master_field, $join_kind, $relation);
    }
412190
public function setListParent($relation, $recordKey = null)
    {
        if (false !== $relation && empty($relation)) {
            return $this->clearListParent();
        }

        if (false === $relation) {
            session()->put($this->getSessionKey(static::TYPE_PARENT), static::PARENT_DISABLE);
        } else {
            session()->put($this->getSessionKey(static::TYPE_PARENT), $relation . ':' . $recordKey);
        }

        return $this;
    }
814352
private function loadRelatedDefinition($version, $resource, $related, $type, $key = null) : string
    {
        $definition = $this->definition($resource, $version);
        $relationDefinition = $definition->relation($related);

        $classPath = $relationDefinition->$type;
        if (is_array($classPath) && array_key_exists($key, $classPath)) {
            $classPath = $classPath[$key];
        }

        if ($classPath === null) {
            throw ResourceNotDefinedException::resource($resource, $type);
        }

        return $classPath;
    }
256329
protected static function _relationsToLoad() {
		try {
			if (!$connection = static::connection()) {
				return;
			}
		} catch (ConfigException $e) {
			return;
		}

		if (!$connection::enabled('relationships')) {
			return;
		}

		$self = static::_object();

		foreach ($self->_relationTypes as $type) {
			$self->$type = Set::normalize($self->$type);
			foreach ($self->$type as $name => $config) {
				$self->_relationsToLoad[$name] = $type;
				$fieldName = $self->_relationFieldName($type, $name);
				$self->_relationFieldNames[$fieldName] = $name;
			}
		}
	}
209269
private function generateIntFieldInput($column, $dbType)
    {
        $field = new GeneratorField();
        $field->name = $column->getName();
        $field->parseDBType($dbType);
        $field->htmlType = 'number';

        if ($column->getAutoincrement()) {
            $field->dbInput .= ',true';
        } else {
            $field->dbInput .= ',false';
        }

        if ($column->getUnsigned()) {
            $field->dbInput .= ',true';
        }

        return $this->checkForPrimary($field);
    }
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));
		}
	}
261995
public static function validateToOneRelation($relation, $relationship)
    {
        if (
            !is_null($relation)
            && !$relation instanceof ResourceEntityInterface
        ) {
            $type = is_object($relation)
                ? get_class($relation) : gettype($relation);
            throw new \Exception(sprintf(
                self::ERROR_NOT_RESOURCE_ENTITY, $relationship, $type
            ));
        }
    }
242702
protected function getDBField($field)
    {
        $dbField = null;
        if (stristr($field, self::SEPARATOR) !== false) {
            list ($relationName, $relationField) = explode(self::SEPARATOR, $field);
            $class = $this->getDataObjectInstance()->getRelationClass($relationName);
            if (!$class) {
                throw new InvalidArgumentException(sprintf(
                    'Could not find relation %s on %s',
                    $relationName,
                    $this->getDataObjectClass()
                ));
            }
            return Injector::inst()->get($class)->dbObject($relationField);
        }

        return $this->getDataObjectInstance()->dbObject($field);
    }
198493
public static function getRelationGridColumns($model, $fields, $relationName, $relation)
    {
        $columns = parent::getRelationGridColumns($model, $fields, $relationName, $relation);
        $controller = Yii::$app->crudModelsMap[$model::className()];
        $actionColumn = new \yii\grid\ActionColumn();

        if (!isset($columns[0]) || !isset($columns[0]['class']) || $columns[0]['class'] !== 'yii\grid\ActionColumn') {
            array_unshift($columns, [
                'class'         => 'yii\grid\ActionColumn',
                'headerOptions' => ['class' => 'column-action'],
                'controller'    => $controller,
                'template'      => '',
                'buttons'       => [],
            ]);
        }

        $columns[0]['template'] = '{update} {unlink}';
        $columns[0]['urlCreator'] = function ($action, $model, $key, $index) use ($controller, $relation) {
            $params = is_array($key) ? $key : ['id' => (string)$key];
            if ($action === 'update') {
                $params['hide'] = implode(',', array_keys($relation->link));
            }
            $params[0] = $controller . '/' . $action;

            return Url::toRoute($params);
        };
        $columns[0]['buttons']['update'] = function ($url, $model, $key) use ($actionColumn, $relationName) {
            /** @var \netis\crud\db\ActiveRecord $model */
            if (!Yii::$app->user->can($model::className() . '.update', ['model' => $model])) {
                return null;
            }

            $options = array_merge([
                'title'         => Yii::t('app', 'Update'),
                'aria-label'    => Yii::t('app', 'Update'),
                'data-pjax'     => '0',
                // required for editing in a modal
                'data-toggle'   => 'modal',
                'data-target'   => '#relationModal',
                'data-relation' => $relationName,
                'data-title'    => $model->getCrudLabel('update'),
                'data-pjax-url' => $url,
                'class'         => 'btn btn-default btn-xs',
            ], $actionColumn->buttonOptions);
            return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, $options);
        };

        /** @var \yii\db\ActiveQuery $relation */
        $remove = false;
        $modelClass = $relation->modelClass;
        foreach (array_keys($relation->link) as $foreignKey) {
            $remove = $remove || !$modelClass::getTableSchema()->getColumn($foreignKey)->allowNull;
        }

        $columns[0]['buttons']['unlink'] = function ($url, $model, $key) use ($actionColumn, $remove) {
            /** @var \netis\crud\db\ActiveRecord $model */
            if (!Yii::$app->user->can($model::className() . ($remove ? '.delete' : '.update'), ['model' => $model])) {
                return null;
            }

            $options = array_merge([
                'title'      => Yii::t('app', 'Unlink'),
                'aria-label' => Yii::t('app', 'Unlink'),
                //'data-confirm' => Yii::t('app', 'Are you sure you want to unlink this item?'),
                'data-pjax'  => '0',
                'class'      => 'remove btn btn-default btn-xs',
            ], $actionColumn->buttonOptions);
            return Html::a('<span class="glyphicon glyphicon-remove"></span>', $url, $options);
        };
        return $columns;
    }
448239
protected function getClassToProxy($relation, array $attributes)
    {
        if ($this->entityMap->isPolymorphic($relation)) {
            $localTypeAttribute = $this->entityMap->getLocalKeys($relation)['type'];

            return $attributes[$localTypeAttribute];
        }

        return $this->entityMap->getTargettedClass($relation);
    }
682091
public function determineFormDisplayStrategy(ModelRelationData $data)
    {
        $type = null;

        switch ($data->type) {

            case RelationType::BELONGS_TO:
            case RelationType::BELONGS_TO_THROUGH:
            case RelationType::MORPH_ONE:
            case RelationType::HAS_ONE:
                $type = FormDisplayStrategy::RELATION_SINGLE_AUTOCOMPLETE;
                break;

            case RelationType::BELONGS_TO_MANY:
            case RelationType::HAS_MANY:
            case RelationType::MORPH_MANY:
            case RelationType::MORPH_TO_MANY:
            case RelationType::MORPHED_BY_MANY:
                $type = FormDisplayStrategy::RELATION_PLURAL_AUTOCOMPLETE;
                break;

            case RelationType::MORPH_TO:
                $type = FormDisplayStrategy::RELATION_SINGLE_MORPH_AUTOCOMPLETE;
                break;
        }

        return $type;
    }
1009301
public function searchDatabase(
        Connection $connection,
        string $databaseName,
        string $searchTerm
    ): \Generator {
        $databaseMetadata = (new MetadataFactory())->getDatabaseMetadata($connection, $databaseName);

        foreach ($databaseMetadata->getAllTableMetadata() as $tableMetadata) {
            $resultList = $this->searchTable(
                $connection,
                $tableMetadata->getDatabaseName(),
                $tableMetadata->getTableName(),
                $searchTerm
            );

            foreach ($resultList as $result) {
                yield $result;
            }
        }
    }
929226
protected function getJoinClause(Model $parent, Relation $relation, $table, $type)
    {
        list($fk, $pk) = $this->getJoinKeys($relation);

        $join = (new Join($this->query, $type, $table))->on($fk, '=', $pk);

        if (in_array(SoftDeletes::class, class_uses_recursive($relation->getRelated()))) {
            $join->whereNull($relation->getRelated()->getQualifiedDeletedAtColumn());
        }

        if ($relation instanceof MorphOneOrMany) {
            $join->where($relation->getQualifiedMorphType(), '=', $parent->getMorphClass());
        } elseif ($relation instanceof MorphToMany || $relation instanceof MorphByMany) {
            $join->where($relation->getMorphType(), '=', $parent->getMorphClass());
        }

        return $join;
    }
74181
public function getRelation(string $relation) : Relationship
    {
        // We want to run a relationship query without any constrains so that we will
        // not have to remove these where clauses manually which gets really hacky
        // and is error prone while we remove the developer's own where clauses.
        $query = Relationship::noConstraints(function () use ($relation) {
            return $this->entityMap->$relation($this->mapper->newInstance());
        });

        $nested = $this->nestedRelations($relation);

        // If there are nested relationships set on the query, we will put those onto
        // the query instances so that they can be handled after this relationship
        // is loaded. In this way they will all trickle down as they are loaded.
        if (count($nested) > 0) {
            $query->getQuery()->with($nested);
        }

        return $query;
    }
761339
public PointerPrototypeHierarchyRepresentationResult run(Database db, Relation<O> relation) {
    DistanceQuery<O> dq = DatabaseUtil.precomputedDistanceQuery(db, relation, getDistanceFunction(), LOG);
    final DBIDs ids = relation.getDBIDs();
    final int size = ids.size();

    // Initialize space for result:
    PointerHierarchyRepresentationBuilder builder = new PointerHierarchyRepresentationBuilder(ids, dq.getDistanceFunction().isSquared());
    Int2ObjectOpenHashMap<ModifiableDBIDs> clusters = new Int2ObjectOpenHashMap<>(size);

    // Allocate working space:
    MatrixParadigm mat = new MatrixParadigm(ids);
    ArrayModifiableDBIDs prots = DBIDUtil.newArray(MatrixParadigm.triangleSize(size));
    initializeMatrices(mat, prots, dq);

    DBIDArrayMIter protiter = prots.iter();
    FiniteProgress progress = LOG.isVerbose() ? new FiniteProgress("MiniMax clustering", size - 1, LOG) : null;
    DBIDArrayIter ix = mat.ix;
    for(int i = 1, end = size; i < size; i++) {
      end = AGNES.shrinkActiveSet(ix, builder, end, //
          findMerge(end, mat, protiter, builder, clusters, dq));
      LOG.incrementProcessed(progress);
    }
    LOG.ensureCompleted(progress);
    return (PointerPrototypeHierarchyRepresentationResult) builder.complete();
  }