Build to one (one to one, many to one) association mapping from class metadata.
347343
private function buildToOneAssociationMappings(Mapping\ClassMetadata $metadata)
    {
        $tableName   = $metadata->getTableName();
        $primaryKeys = $this->getTablePrimaryKeys($this->tables[$tableName]);
        $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]);

        foreach ($foreignKeys as $foreignKey) {
            $foreignTableName   = $foreignKey->getForeignTableName();
            $fkColumns          = $foreignKey->getColumns();
            $fkForeignColumns   = $foreignKey->getForeignColumns();
            $localColumn        = current($fkColumns);
            $associationMapping = [
                'fieldName'    => $this->getFieldNameForColumn($tableName, $localColumn, true),
                'targetEntity' => $this->getClassNameForTable($foreignTableName),
            ];

            if ($metadata->getProperty($associationMapping['fieldName'])) {
                $associationMapping['fieldName'] .= '2'; // "foo" => "foo2"
            }

            if ($primaryKeys && in_array($localColumn, $primaryKeys, true)) {
                $associationMapping['id'] = true;
            }

            for ($i = 0, $l = count($fkColumns); $i < $l; $i++) {
                $joinColumn = new Mapping\JoinColumnMetadata();

                $joinColumn->setColumnName($fkColumns[$i]);
                $joinColumn->setReferencedColumnName($fkForeignColumns[$i]);

                $associationMapping['joinColumns'][] = $joinColumn;
            }

            // Here we need to check if $fkColumns are the same as $primaryKeys
            if (! array_diff($fkColumns, $primaryKeys)) {
                $metadata->addProperty($associationMapping);
            } else {
                $metadata->addProperty($associationMapping);
            }
        }
    }
541357
function mapRelation(rel, modelName, relName) {
    let acceptingParams = Object.assign({}, {
        filter: {
            generated: false,
            type: 'JSON'
        }
    }, connectionArgs);
    types[modelName].meta.fields[relName] = {
        generated: true,
        meta: {
            relation: true,
            connection: true,
            relationType: rel.type,
            isMany: isManyRelation(rel.type),
            embed: rel.embed,
            type: rel.modelTo.modelName,
            args: acceptingParams,
        },
        resolve: (obj, args, context, info) => {

            const ctxOptions = { accessToken: context.req.accessToken }
            const modelId = args && args.id;

            const method = rel.modelTo.sharedClass.findMethodByName('find');
            // TODO: ...
            return new Promise((resolve, reject) => { resolve(true) }).then(() => {
                let params = {};

                _.forEach(acceptingParams, (param, name) => {
                    if (typeof args[name] !== 'undefined' && Object.keys(args[name]).length > 0) {
                        _.merge(params, _.cloneDeep(args[name]));
                    }
                });

                if (isManyRelation(rel.type) === true) {
                    return connectionFromPromisedArray(findRelatedMany(rel, obj, params, context), args, rel.modelTo);
                } else {
                    return findRelatedOne(rel, obj, params, context);
                }

                // let wrap = promisify(model[method.name](...params, ctxOptions));

                // if (typeObj.list) {
                //     return connectionFromPromisedArray(wrap, args, model);
                // } else {
                //     return wrap;
                // }


            }).catch((err) => {
                throw err;
            });
        }
    };
}
283875
public static Map<String, String> toMap(List<EntityMetadata> metadata) {
		
		Map<String, String> map = new LinkedHashMap<String, String>();
		
		if(CollectionUtils.isNotEmpty(metadata)) {
			
			for(EntityMetadata m : metadata) {
				
				map.put(m.getName(), m.getValue());
				
			}
		
		}
		
		return map;
		
	}
1118861
private Pair<Map<String, Model>, Map<String, Set<String>>> fetchModels() {
    Map<String, Model> all_models = null;
    Map<String, Set<String>> all_models_cols = null;

    if (this.find_compatible_models) {
      // caches for this request
      all_models = (new Models()).fetchAll();
      all_models_cols = new TreeMap<String, Set<String>>();

      for (Map.Entry<String, Model> entry : all_models.entrySet()) {
        all_models_cols.put(entry.getKey(), new TreeSet<String>(Arrays.asList(entry.getValue()._names)));
      }
    }
    return new Pair<Map<String, Model>, Map<String, Set<String>>>(all_models, all_models_cols);
  }
1346512
def _build_instance_handler_mapping(cls, instance, handle_d):
        """"""
        res = {}
        for member_name, sig_name in handle_d.items():
            if sig_name in res:
                sig_handlers = res[sig_name]
            else:
                sig_handlers = res[sig_name] = []
            sig_handlers.append(getattr(instance, member_name))
        return res
806756
protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = $this->spaces . '/**';

        if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) {
            $lines[] = $this->spaces . ' * @var \Doctrine\Common\Collections\Collection';
        } else {
            $lines[] = $this->spaces . ' * @var \\' . ltrim($associationMapping['targetEntity'], '\\');
        }

        if ($this->generateAnnotations) {
            $lines[] = $this->spaces . ' *';

            if (isset($associationMapping['id']) && $associationMapping['id']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';

                if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
                    $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
                }
            }

            $type = null;
            switch ($associationMapping['type']) {
                case ClassMetadataInfo::ONE_TO_ONE:
                    $type = 'OneToOne';
                    break;
                case ClassMetadataInfo::MANY_TO_ONE:
                    $type = 'ManyToOne';
                    break;
                case ClassMetadataInfo::ONE_TO_MANY:
                    $type = 'OneToMany';
                    break;
                case ClassMetadataInfo::MANY_TO_MANY:
                    $type = 'ManyToMany';
                    break;
            }
            $typeOptions = array();

            if (isset($associationMapping['targetEntity'])) {
                $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"';
            }

            if (isset($associationMapping['inversedBy'])) {
                $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"';
            }

            if (isset($associationMapping['mappedBy'])) {
                $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"';
            }

            if ($associationMapping['cascade']) {
                $cascades = array();

                if ($associationMapping['isCascadePersist']) $cascades[] = '"persist"';
                if ($associationMapping['isCascadeRemove']) $cascades[] = '"remove"';
                if ($associationMapping['isCascadeDetach']) $cascades[] = '"detach"';
                if ($associationMapping['isCascadeMerge']) $cascades[] = '"merge"';
                if ($associationMapping['isCascadeRefresh']) $cascades[] = '"refresh"';

                if (count($cascades) === 5) {
                    $cascades = array('"all"');
                }

                $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}';
            }

            if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) {
                $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false');
            }

            if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) {
                $fetchMap = array(
                    ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY',
                    ClassMetadataInfo::FETCH_EAGER      => 'EAGER',
                );

                $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"';
            }

            $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')';

            if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinColumns'] as $joinColumn) {
                    if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) {
                        $joinColumnsLines[] = $this->spaces . ' *   ' . $joinColumnAnnot;
                    }
                }

                $lines[] = implode(",\n", $joinColumnsLines);
                $lines[] = $this->spaces . ' * })';
            }

            if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) {
                $joinTable = array();
                $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"';

                if (isset($associationMapping['joinTable']['schema'])) {
                    $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"';
                }

                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ',';
                $lines[] = $this->spaces . ' *   joinColumns={';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) {
                    $joinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $joinColumnsLines);
                $lines[] = $this->spaces . ' *   },';
                $lines[] = $this->spaces . ' *   inverseJoinColumns={';

                $inverseJoinColumnsLines = array();

                foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
                    $inverseJoinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines);
                $lines[] = $this->spaces . ' *   }';
                $lines[] = $this->spaces . ' * )';
            }

            if (isset($associationMapping['orderBy'])) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({';

                foreach ($associationMapping['orderBy'] as $name => $direction) {
                    $lines[] = $this->spaces . ' *     "' . $name . '"="' . $direction . '",';
                }

                $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1);
                $lines[] = $this->spaces . ' * })';
            }
        }

        $lines[] = $this->spaces . ' */';

        return implode("\n", $lines);
    }
53667
def add_association(name, type, metadata={})
      associations << (metadata || {}).merge(:name => name.to_sym, :type => type.to_sym)
    end
1296409
def mapped(cls, key='id', **kwargs):
    """"""
    kwargs.setdefault('metadata', {})
    kwargs['metadata']['jsonldPredicate'] = {'mapSubject': key}
    kwargs.setdefault('default', attr.Factory(list))

    def converter(value):
        """Convert mapping to a list of instances."""
        if isinstance(value, dict):
            result = []
            for k, v in iteritems(value):
                if not hasattr(cls, 'from_cwl'):
                    vv = dict(v)
                    vv[key] = k
                else:
                    vv = attr.evolve(cls.from_cwl(v), **{key: k})
                result.append(vv)
        else:
            result = value

        def fix_keys(data):
            """Fix names of keys."""
            for a in fields(cls):
                a_name = a.name.rstrip('_')
                if a_name in data:
                    yield a.name, data[a_name]

        return [
            cls(**{kk: vv
                   for kk, vv in fix_keys(v)}) if not isinstance(v, cls) else v
            for v in result
        ]

    kwargs['converter'] = converter
    return attr.ib(**kwargs)
866859
def meta(cls):
        """"""
        if getattr(cls, '__from_class__', None) is not None:
            cls = cls.__from_class__
        attribute_info = {}
        for name, value in cls.__table__.columns.items():
            attribute_info[name] = str(value.type).lower()

        return {cls.__name__: attribute_info}
758342
private <X> void populateRelationMetaData(EntityType entityType, Class<X> clazz, EntityMetadata metadata)
    {
        Set<Attribute> attributes = entityType.getAttributes();

        for (Attribute attribute : attributes)
        {
            if (attribute.isAssociation())
            {

                addRelationIntoMetadata(clazz, (Field) attribute.getJavaMember(), metadata);
            }
        }

    }
11522
private function getInheritanceAssociations(ClassMetadata $class, $associations = array())
    {
        if ($parent = $this->classStore->getParent($class)) {
            foreach ($parent->getAssociationNames() as $association) {
                if (!in_array($association, $associations)) {
                    $associations[] = $association;
                }
            }
            $associations = $this->getInheritanceAssociations($parent, $associations);
        }

        return $associations;
    }
677679
def build(associations, base_klass)
      associations.map do |name, right|
        if name.is_a? Join
          reflection = find_reflection base_klass, name.name
          reflection.check_validity!
          reflection.check_eager_loadable!

          klass = if reflection.polymorphic?
            name.klass || base_klass
          else
            reflection.klass
          end
          JoinAssociation.new(reflection, build(right, klass), alias_tracker, name.klass, name.type)
        else
          reflection = find_reflection base_klass, name
          reflection.check_validity!
          reflection.check_eager_loadable!

          if reflection.polymorphic?
            raise ActiveRecord::EagerLoadPolymorphicError.new(reflection)
          end
          JoinAssociation.new(reflection, build(right, reflection.klass), alias_tracker)
        end
      end
    end
485674
def associations
      @associations ||= Hash[metadata.xpath('//Association').collect do |association_definition|
        [
            association_definition.attributes['Name'].value,
            build_association(association_definition)
        ]
      end]
    end
400462
def build(cls: Type[T], data: Generic) -> T:
        """"""
        fields = fields_dict(cls)
        kwargs: Dict[str, Any] = {}
        for key, value in data.items():
            if key in fields:
                if isinstance(value, Mapping):
                    t = fields[key].type
                    if issubclass(t, Auto):
                        value = t.build(value)
                    else:
                        value = Auto.generate(value, name=key.title())
                kwargs[key] = value
            else:
                log.debug(f"got unknown attribute {key} for {cls.__name__}")
        return cls(**kwargs)
484387
def from_mapping(cls, mapping):
        
        group = cls()
        for name, value in mapping.items():
            if name.startswith('_'):
                continue
            group[name] = Parameter(
                name=name,
                value=value,
                constraint=Parameter.constraint_from_type(value),
            )
        return group
640544
def load_related(self, meta, fname, data, fields, encoding):
        ''''''
        field = meta.dfields[fname]
        if field in meta.multifields:
            fmeta = field.structure_class()._meta
            if fmeta.name in ('hashtable', 'zset'):
                return ((native_str(id, encoding),
                         pairs_to_dict(fdata, encoding)) for
                        id, fdata in data)
            else:
                return ((native_str(id, encoding), fdata) for
                        id, fdata in data)
        else:
            # this is data for stdmodel instances
            return self.build(data, meta, fields, fields, encoding)
828128
def map_to(klass, **opts)
      with(opts.merge(auto_map: false, auto_struct: true, meta: { model: klass }))
    end