solves the relations for a single field and generate dql for select and joins.

@param string $field
@param string $prefix
19451
private function performSelectFromField($field, $prefix = 'u')
    {
        // Relation name and field delimited by underscore
        $fieldParts = explode('_', $field);

        // temporary variable for saving field name (needed for array results like [0])
        $realFieldName = $field;
        // check if a certain field number is searched
        if (preg_match('/^(.*)\[(\d+)\]$/', $fieldParts[0], $regresult)) {
            $fieldParts[0] = $regresult[1];
            $realFieldName = implode('_', $fieldParts);
            $this->relationalFilters[$realFieldName] = $regresult[2];
        }

        // If field is delimited and is a Relation
        if (count($fieldParts) >= 2 && $this->isRelation($fieldParts[0])) {
            $this->joins .= $this->generateJoins($fieldParts, $prefix);
            if (in_array($field, $this->fields)) {
                // last element is column name and next-to-last is the associationPrefix
                $i = count($fieldParts) - 1;

                // {associationPrefix}.{columnName} {alias}
                $parent = $fieldParts[$i - 1];
                $tempField = $fieldParts[$i];
                $alias = $realFieldName;

                $this->addToSelect($parent, $tempField, $alias);
            }
        } elseif (in_array($field, $this->fields) && in_array($field, $this->fieldNames)) {
            $this->addToSelect($prefix, $field);
        }
    }
234071
private function applyNestedFilter(Builder $query, array $fields, $operator, $value, $or = false)
    {
        $relation_name = implode('.', array_slice($fields, 0, count($fields) - 1));
        $relation_field = end($fields);
        if ($relation_name[0] == '!') {
            $relation_name = substr($relation_name, 1, strlen($relation_name));

            $that = $this;

            return $query->whereHas($relation_name, function ($query) use ($relation_field, $operator, $value, $that, $or) {
                $query = $that->applyWhereClause($query, $relation_field, $operator, $value, $or);
            }, '=', 0);
        }

        $that = $this;

        return $query->whereHas($relation_name, function ($query) use ($relation_field, $operator, $value, $that, $or) {
            $query = $that->applyWhereClause($query, $relation_field, $operator, $value, $or);
        });
    }
1294008
private function stripRelationPrefix(array $records, $prefix)
    {
        //Strip the relation prefix from the columns
        foreach ($records as $record) {
            yield Utils::filterPrefixedElements(
                $record,
                $prefix,
                Utils::FILTER_REMOVE_PREFIX | Utils::FILTER_USE_KEYS
            );
        }
    }
161778
private function applyFieldFilter(Builder $query, $field, $value)
    {
        $query = $this->resolveOrLinks($query, $field, $value);

        return $query;
    }
511633
private function applyCriteriaToQueryBuilder(Criteria $criteria, QueryBuilder $qb, $prefix)
    {
        if ($criteria->getMode() === Criteria::MODE_OR) {
            $expr = $qb->expr()->orX();
        } else {
            $expr = $qb->expr()->andX();
        }
        foreach ($criteria as $criterium) {
            if ($criterium instanceof Criteria) {
                $expr->add(
                    $this->applyCriteriaToQueryBuilder($criterium, $qb, $prefix)
                );
            } else {
                $this->applyCriteriumToQueryBuilder($criterium, $qb, $expr, $prefix);
            }
        }

        return $expr;
    }
1356258
public function foreignKeys($prefix = null) {
		$tables = $this->_getTables($prefix);

		$todo = [];

		$db = $this->_getConnection();
		foreach ($tables as $table) {
			// Structure
			$sql = 'DESCRIBE ' . $table['table_name'] . ';';
			$this->out('- ' . $sql, 1, static::VERBOSE);

			/** @var \Cake\Database\Statement\StatementDecorator $res */
			$res = $db->query($sql);
			$fields = new Collection($res);

			$fieldList = [];
			foreach ($fields as $field) {
				$name = $field['Field'];
				$type = $field['Type'];
				$null = $field['Null'];
				if (!preg_match('/\w+\_id$/', $name) || !preg_match('/^int\(1[10]\)|char\(36\)|varchar\(36\)/', $type)) {
					continue;
				}

				$fieldList[] = $field['Field'];

				$isUuid = $type === 'char(36)' || $type === 'varchar(36)';
				if ($null === 'YES' && $field['Default'] === null) {
					continue;
				}

				if (!empty($field['Key']) && $field['Key'] === 'PRI') {
					continue;
				}
				if (!empty($field['Extra']) && $field['Extra'] === 'auto_increment') {
					continue;
				}

				// We need to migrate sth
				$todo[] = 'ALTER TABLE' . ' ' . $table['table_name'] . ' CHANGE `' . $name . '` `' . $name . '` ' . $type . ' NULL DEFAULT NULL;';
			}

			if (empty($fieldList)) {
				continue;
			}

			// Data
			$z = '0';
			$conditions = [];
			foreach ($fieldList as $fieldName) {
				$conditions[] = '`' . $fieldName . "` = '" . $z . "'";
			}
			$conditions = implode(' OR ', $conditions);

			$sql = 'SELECT COUNT(*) as count FROM ' . $table['table_name'] . ' WHERE ' . $conditions;
			$this->out('Checking for records that need updating:', 1, static::VERBOSE);
			$this->out(' - ' . $sql, 1, static::VERBOSE);
			/** @var \Cake\Database\Statement\StatementDecorator $res */
			$res = $db->query($sql);
			$res = (new Collection($res))->toArray();
			if (empty($res[0]['count'])) {
				continue;
			}

			$sets = [];
			foreach ($fieldList as $fieldName) {
				$todo[] = 'UPDATE ' . $table['table_name'] . ' SET ' . '`' . $fieldName . '` = NULL' . ' WHERE `' . $fieldName . '` = \'' . $z . '\';';
			}
		}

		if (!$todo) {
			$this->out('Nothing to do :)');
			return;
		}

		$this->out(count($todo) . ' tables/fields need updating.');

		if (!$this->param('dry-run')) {
			$continue = $this->in('Continue?', ['Y', 'N'], 'Y');
			if ($continue !== 'Y') {
				$this->abort('Aborted!');
			}
		}

		$sql = implode(PHP_EOL, $todo);
		if (!empty($this->params['dry-run'])) {
			$this->out($sql);
			return;
		}

		// Execute
		$db->query($sql);
		$this->out('Done :)');
	}
268725
public function add_prefix($field) {
        if (substr($field, 0, 2) === '!_') {
            return '-_' . $this->extraprefix . substr($field, 2);
        } else if (substr($field, 0, 1) === '-') {
            return '-' . $this->extraprefix . substr($field, 1);
        } else if (substr($field, 0, 1) === '_') {
            return '_' . $this->extraprefix . substr($field, 1);
        } else {
            return $this->extraprefix . $field;
        }
    }
823780
public function field($field, $alias = null) {
        if (is_string($field)) {
            $fields = explode(',', trim($field));
            foreach ($fields as $field) {
                $this->fields [] = Condition::cleanField($field . ($alias ? ' AS ' . $alias : ''));
            }
        } else if ($field instanceof Query) {
            if ($alias) {
                $field->alias($alias);
            }
            $this->fields [] = $field;
        } else if ($field instanceof ImmutableValue) {
            if ($alias) {
                $field->alias($alias);
            }
            $this->fields [] = $field;
        }

        return $this;
    }
422600
public function fillSchemaFields($values, $map = null, $prefix = null)
    {
        //
        if (is_array($map)) {
            foreach ($map as $alias => $field) {
                if (isset($values[$alias])) {
                    $values[$field] = $values[$alias];
                }
            }
        }

        //
        foreach (static::getSchema() as $field => $aspects) {
            if (isset($aspects['Class']) && $aspects['Relation'] == '1:1') {
                $class = $aspects['Class'];

                $this->{$field} = $class::create(
                    $values,
                    $map,
                    $prefix.$field.'__'
                );
            }

            //
            $field = $prefix.$field;

            //
            if (isset($values[$field])) {
                $this->{$field} = $values[$field];
            }
        }

        //
        $key = $this->getPrimaryKey();

        //
        $field = $prefix.$key;

        //
        if ($key) {
            $this->{$key} = isset($values[$field])
                ? (int) $values[$field]
                : (int) $this->{$key};
        }
    }
39398
protected function assertField($field)
    {
        if (empty($field)) {
            throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be empty', $this->entity, $field));
        }

        if (is_numeric($field)) {
            throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" can not be numeric', $this->entity, $field));
        }

        if (!is_string($field)) {
            throw new DefinitionException(sprintf('Invalid field name for relation "%s.%s" must be string, %s given', $this->entity, $field, $this->getType($field)));
        }
    }
214309
private function generateJoinCondition($field)
    {
        if (!array_key_exists($field, $this->joinConditions)) {
            return '';
        }

        // ON {joinConditino}
        $format = ' WITH %s';

        return sprintf($format, $this->joinConditions[$field]);
    }
196145
public List<Field> resolveFieldsWithPrefix(Optional<QualifiedName> prefix)
    {
        return visibleFields.stream()
                .filter(input -> input.matchesPrefix(prefix))
                .collect(toImmutableList());
    }
975119
private function render(Field $field)
    {
        $field->set('lang', $this->language);
        $field->set('prefix', $this->buildPrefix($field));

        foreach ($this->fill($field->getAttributes()) as $key => $value) {
            $field->set($key, $value);
        }

        return $field->render();
    }
501679
public function _prefix($name, $prefix)
    {
        list($alias, $field) = $this->undot($name);
        return $alias ? $name : "{$prefix}.{$field}";
    }
379061
private function setLeftJoin($table, $field, $parentField, $alias, $parentAlias, $withWhere = false)
    {
        if (!in_array($alias, $this->tables)) {
            $condition = $this->getFullFieldName($field, $alias).' = '.$this->getFullFieldName($parentField, $parentAlias);
            $this->queryBuilder->leftJoin($table, $alias, 'WITH', $condition);
            if ($withWhere) {
                $this->queryBuilder->andWhere($condition);
            }
            $this->tables[] = $alias;
        }
    }
906053
public function getRelationIds(Field $field)
    {
        if (!$this->accept($field)) {
            $identifier = $this->getSupportedFieldTypeIdentifier();

            throw new LogicException(
                "This resolver can only handle fields of '{$identifier}' type"
            );
        }

        return $this->getRelationIdsFromValue($field->value);
    }
1140326
public function initRelation($model, $field = null)
    {
        if ($field == null) {
            $field = post(self::PARAM_FIELD);
        }

        $this->config = $this->originalConfig;
        $this->model = $model;
        $this->field = $field;

        if ($field == null) {
            return;
        }

        if (!$this->model) {
            throw new ApplicationException(Lang::get(
                'backend::lang.relation.missing_model',
                ['class'=>get_class($this->controller)]
            ));
        }

        if (!$this->model instanceof Model) {
            throw new ApplicationException(Lang::get(
                'backend::lang.model.invalid_class',
                ['model'=>get_class($this->model), 'class'=>get_class($this->controller)]
            ));
        }

        if (!$this->getConfig($field)) {
            throw new ApplicationException(Lang::get('backend::lang.relation.missing_definition', compact('field')));
        }

        if ($extraConfig = post(self::PARAM_EXTRA_CONFIG)) {
            $this->applyExtraConfig($extraConfig);
        }

        $this->alias = camel_case('relation ' . $field);
        $this->config = $this->makeConfig($this->getConfig($field), $this->requiredRelationProperties);
        $this->controller->relationExtendConfig($this->config, $this->field, $this->model);

        /*
         * Relationship details
         */
        $this->relationName = $field;
        $this->relationType = $this->model->getRelationType($field);
        $this->relationObject = $this->model->{$field}();
        $this->relationModel = $this->relationObject->getRelated();

        $this->manageId = post('manage_id');
        $this->foreignId = post('foreign_id');
        $this->readOnly = $this->getConfig('readOnly');
        $this->deferredBinding = $this->getConfig('deferredBinding') || !$this->model->exists;
        $this->viewMode = $this->evalViewMode();
        $this->manageMode = $this->evalManageMode();
        $this->manageTitle = $this->evalManageTitle();
        $this->toolbarButtons = $this->evalToolbarButtons();

        /*
         * Toolbar widget
         */
        if ($this->toolbarWidget = $this->makeToolbarWidget()) {
            $this->toolbarWidget->bindToController();
        }

        /*
         * Search widget
         */
        if ($this->searchWidget = $this->makeSearchWidget()) {
            $this->searchWidget->bindToController();
        }

        /*
         * View widget
         */
        if ($this->viewWidget = $this->makeViewWidget()) {
            $this->controller->relationExtendViewWidget($this->viewWidget, $this->field, $this->model);
            $this->viewWidget->bindToController();
        }

        /*
         * Manage widget
         */
        if ($this->manageWidget = $this->makeManageWidget()) {
            $this->controller->relationExtendManageWidget($this->manageWidget, $this->field, $this->model);
            $this->manageWidget->bindToController();
        }

        /*
         * Pivot widget
         */
        if ($this->manageMode == 'pivot' && $this->pivotWidget = $this->makePivotWidget()) {
            $this->controller->relationExtendPivotWidget($this->pivotWidget, $this->field, $this->model);
            $this->pivotWidget->bindToController();
        }
    }