Find out the primary key for given model field path.

@param  string $model     The starting model.
@param  string $fieldPath The field path.
@return string The leaf field's primary key.
505473
public function getPrimaryKeyFor($model, $fieldPath)
    {
        $resolved = $this->resolveRelatedField($model, $fieldPath);
        $class = $resolved['class'];
        $field = $resolved['field'];

        if ($relation = $this->getRelation($field, $class)) {
            $class = $relation->getLocalTable()->getClassname();

            return $this->getModelPrimaryKeyName($class);
        } else {
            // if the leaf node is not an association
            return null;
        }
    }
193582
public function asNode(Model $model)
    {
        $node = $this->client->makeNode();

        // If the key name of the model is 'id' we will need to set it properly with setId()
        // since setting it as a regular property with setProperty() won't cut it.
        if ($model->getKeyName() == 'id')
        {
            $node->setId($model->getKey());
        }

        // In this case the dev has chosen a different primary key
        // so we use it insetead.
        else
        {
            $node->setProperty($model->getKeyName(), $model->getKey());
        }

        return $node;
    }
669567
public function getMigrationPath($table, $field = null)
    {
        $name = is_null($field) ?
            $this->getTableMigrationName($table) :
            $this->getTableFieldMigrationName($field, $table);

        return sprintf(
            $this->getBasePath() . '/%s.php',
            $name);
    }
1341870
public static function getModelKeys($model, $includePrimary = true)
    {
        $keys = array_map(function ($foreignKey) {
            array_shift($foreignKey);
            return array_keys($foreignKey);
        }, $model->getTableSchema()->foreignKeys);
        if ($includePrimary) {
            $keys[] = $model->primaryKey();
        }
        return call_user_func_array('array_merge', $keys);
    }
171899
private String evaluateFieldPath(MappedFieldMetaData fieldMetaData) {
        ResourcePaths.ResourcePath path = fieldMetaData.getPath();
        return (path.hasPlaceholders() ? path.resolve(this.placeholderVariableResolvers::resolve) : path).getPath();
    }
1352193
protected function getBlameableFields(Model $model)
    {
        if (isset($this->fields)) {
            return $this->fields;
        }

        $this->fields = self::findBlameableFields($model);

        return $this->fields;
    }
198665
protected function resolveFieldChain($fieldPath)
    {
        if (isset($this->resolvedFieldChains[$fieldPath])) {
            return $this->resolvedFieldChains[$fieldPath];
        }

        $result = [];
        $pathInfo = explode(self::FIELD_SEPARATOR, $fieldPath);

        $latestCollection = $this->collection;
        $fieldSourceAlias = $this->collection->getSourceAlias();

        for ($i = 0; $i < count($pathInfo); $i++) {
            $fieldName = $pathInfo[$i];

            /**
             * @var IMetadata $metadata
             */
            $metadata = $latestCollection->getMetadata();
            if (!$metadata->getFieldExists($fieldName)) {
                throw new InvalidArgumentException($this->translate(
                    'Cannot resolve field path "{path}". Field "{name}" does not exist in "{metadata}".',
                    ["path" => $fieldPath, "name" => $fieldName, "metadata" => $metadata->getCollectionName()]
                ));
            }

            $field = $metadata->getField($fieldName);
            $result[] = [$field, $fieldSourceAlias, $latestCollection];

            if ($i == 0) {
                $this->usedFields[$field->getName()] = $field;
            }

            if ($field instanceof IRelationField) {
                $latestCollection = $field->getTargetCollection();
                $fieldSourceAlias .= self::ALIAS_SEPARATOR . $fieldName;

                if (!isset($pathInfo[$i + 1])) {
                    $latestCollectionIdField = $latestCollection->getIdentifyField();
                    $result[] = [$latestCollectionIdField, $fieldSourceAlias, $latestCollection];
                }
            } elseif (isset($pathInfo[$i + 1])) {
                throw new InvalidArgumentException($this->translate(
                    'Cannot resolve field path "{path}". Field "{name}" is not relation.',
                    ["path" => $fieldPath, "name" => $field->getName()]
                ));
            }
        }

        return $this->resolvedFieldChains[$fieldPath] = $result;
    }
662441
def get_path_fields(self, path, method, view):
        
        model = getattr(getattr(view, 'queryset', None), 'model', None)
        fields = []

        for variable in uritemplate.variables(path):

            if variable == 'version':
                continue

            title = ''
            description = ''
            schema_cls = coreschema.String
            kwargs = {}
            if model is not None:
                # Attempt to infer a field description if possible.
                try:
                    model_field = model._meta.get_field(variable)
                except:
                    model_field = None

                if model_field is not None and model_field.verbose_name:
                    title = force_text(model_field.verbose_name)

                if model_field is not None and model_field.help_text:
                    description = force_text(model_field.help_text)
                elif model_field is not None and model_field.primary_key:
                    description = get_pk_description(model, model_field)

                if hasattr(view, 'lookup_value_regex') and view.lookup_field == variable:
                    kwargs['pattern'] = view.lookup_value_regex
                elif isinstance(model_field, models.AutoField):
                    schema_cls = coreschema.Integer

            field = Field(
                name=variable,
                location='path',
                required=True,
                schema=schema_cls(title=title, description=description, **kwargs)
            )
            fields.append(field)

        return fields
1201351
public function createModel($model)
    {
        $schema = new Schema();

        $tableDef = $schema->createTable($model->getMeta()->getDbTable());
        // this assumes fields set_from_name has been invoked
        $primaryKeyFields = [];
        $unique_fields = [];
        $indexes = [];
        /** @var $field Field */
        /** @var $field ForeignKey */
        foreach ($model->getMeta()->localFields as $fname => $field) {
            $colName = $field->getColumnName();
            $type = $field->dbType($this->connection);
            // if we don't have a type skip
            if (empty($type)) {
                continue;
            }
            if ($field->primaryKey) {
                $primaryKeyFields[] = $model->getMeta()->primaryKey->getColumnName();
            } elseif ($field->isUnique()) {
                $unique_fields[] = $colName;
            } elseif ($field->dbIndex) {
                $indexes[] = $colName;
            }
            $tableDef->addColumn($colName, $type, $this->getDoctrineColumnOptions($field));
            if ($field->isRelation && $field->relation && $field->dbConstraint) {
                $relField = $field->getRelatedField();
                $tableDef->addForeignKeyConstraint(
                    $relField->scopeModel->getMeta()->getDbTable(),
                    [$field->getColumnName()],
                    [$relField->getColumnName()]
                );
            }
        }
        // create the primary key
        $tableDef->setPrimaryKey($primaryKeyFields);
        // add index constraint
        if (!empty($indexes)) {
            $tableDef->addIndex($indexes);
        }
        // add unique constraint
        if (!empty($unique_fields)) {
            $tableDef->addUniqueIndex($unique_fields);
        }
        $this->createTable($tableDef);
        // many to many
        /** @var $relationField ManyToManyField */
        foreach ($model->getMeta()->localManyToMany as $name => $relationField) {
            if ($relationField->manyToMany && $relationField->relation->through->getMeta()->autoCreated) {
                $this->createModel($relationField->relation->through);
            }
        }
    }
1339927
protected function getPrimaryKeyName(array $fields)
    {
        $primaryKey = $this->getPrimaryField($fields);

        return !is_null($primaryKey) ? $primaryKey->name : null;
    }
679343
protected function getPrimaryKeyName(Field $primaryField = null, $primaryKey = 'id')
    {
        return !is_null($primaryField) ? $primaryField->name : $primaryKey;
    }
663688
protected function makeModelFqnFromCmsModelPath($path)
    {
        $extension = pathinfo($path, PATHINFO_EXTENSION);

        if ($extension) {
            $path = substr($path, 0, -1 * strlen($extension) - 1);
        }

        return rtrim(config('cms-models.collector.source.models-namespace'), '\\')
             . '\\' . str_replace('/', '\\', $path);
    }
365240
private static function validateString($fieldPath)
    {
        if (strpos($fieldPath, '..')) {
            throw new \InvalidArgumentException('Paths cannot contain `..`.');
        }

        if (strpos($fieldPath, '.') === 0 || strpos(strrev($fieldPath), '.') === 0) {
            throw new \InvalidArgumentException('Paths cannot begin or end with `.`.');
        }
    }
140589
protected function getModelByPath($path)
    {
        $model = $this->getModel();

        $relations = explode('.', $path);
        $count = count($relations);
        $i = 1;

        if ($count > 1) {
            $i++;
            $previousModel = $model;

            /* @var Model $model */
            foreach ($relations as $relation) {
                $relatedModel = null;
                if ($previousModel->getAttribute($relation) instanceof Model) {
                    $relatedModel = $previousModel->getAttribute($relation);
                } elseif (method_exists($previousModel, $relation)) {

                    /* @var Relation $relation */
                    $relationObject = $previousModel->{$relation}();

                    switch (get_class($relationObject)) {
                        case BelongsTo::class:
                            $relationObject->associate($relatedModel = $relationObject->getRelated());
                            break;
                        case HasOne::class:
                        case MorphOne::class:
                            $relatedModel = $relationObject->getRelated()->newInstance();
                            $relatedModel->setAttribute($this->getForeignKeyNameFromRelation($relationObject), $relationObject->getParentKey());
                            $model->setRelation($relation, $relatedModel);
                            break;
                    }
                }

                $previousModel = $relatedModel;
                if ($i === $count) {
                    break;
                } elseif (is_null($relatedModel)) {
                    throw new LogicException("Field [{$path}] can't be mapped to relations of model ".get_class($model).'. Probably some dot delimeted segment is not a supported relation type');
                }
            }

            $model = $previousModel;
        }

        return $model;
    }
29189
public function load(DOMNode $field, DOMXPath $rootPath)
    {
        $this->setId($field->attributes->getNamedItem('id')->nodeValue);

        return $this
            ->loadMigrationCalls($field, $rootPath, $this->typeEvals)
            ->loadMigrationCalls($field, $rootPath, $this->optionEvals, true);
    }
971008
protected function getModelsByKey($model, $keys)
    {
        if (is_string($model)) {
            $model = new $model;
        }

        /** @var Model $model */
        return $model->withoutGlobalScopes()
            ->whereIn($model->getKeyName(), $keys)
            ->get()
            ->keyBy($model->getKeyName());
    }
1321389
private function getField($fieldname)
    {
        if (array_key_exists($fieldname, $this->colmodel)) {
            return $this->colmodel[$fieldname];
        } else {
            return false;
        }
    }