Set the foreign ID and type for creation a related model.
433142
def _set_foreign_attributes_for_create(self, model):
        
        model.set_attribute(self.get_plain_foreign_key(), self.get_parent_key())

        model.set_attribute(self.get_plain_morph_type(), self._morph_class)
921941
public function initForeignKeys()
    {
        $elems = $this->node->xpath("value[@key='foreignKeys']");
        $this->foreignKeys = $this->getFormatter()->createForeignKeys($this, $elems[0]);

        return $this;
    }
1215207
private void createForeignKeys(Set<ForeignKey> allForeignKeys, Map<Column, ColumnDescriptor> allColumns, Store store) {
        // Foreign keys
        for (ForeignKey foreignKey : allForeignKeys) {
            ForeignKeyDescriptor foreignKeyDescriptor = store.create(ForeignKeyDescriptor.class);
            foreignKeyDescriptor.setName(foreignKey.getName());
            foreignKeyDescriptor.setDeferrability(foreignKey.getDeferrability().name());
            foreignKeyDescriptor.setDeleteRule(foreignKey.getDeleteRule().name());
            foreignKeyDescriptor.setUpdateRule(foreignKey.getUpdateRule().name());
            for (ForeignKeyColumnReference columnReference : foreignKey.getColumnReferences()) {
                ForeignKeyReferenceDescriptor keyReferenceDescriptor = store.create(ForeignKeyReferenceDescriptor.class);
                // foreign key table and column
                Column foreignKeyColumn = columnReference.getForeignKeyColumn();
                ColumnDescriptor foreignKeyColumnDescriptor = allColumns.get(foreignKeyColumn);
                keyReferenceDescriptor.setForeignKeyColumn(foreignKeyColumnDescriptor);
                // primary key table and column
                Column primaryKeyColumn = columnReference.getPrimaryKeyColumn();
                ColumnDescriptor primaryKeyColumnDescriptor = allColumns.get(primaryKeyColumn);
                keyReferenceDescriptor.setPrimaryKeyColumn(primaryKeyColumnDescriptor);
                foreignKeyDescriptor.getForeignKeyReferences().add(keyReferenceDescriptor);
            }
        }
    }
439668
def init(req, model):
    

    fields = model.all_fields
    rels = model.relationships
    params = []

    for key, val in req.params.items():
        try:
            field, oper = _parse_param(key)
        except (TypeError, ValueError):
            continue

        try:
            local_field, foreign_filter = field.split('/')
            field_type = getattr(model, local_field)

            foreign_field = field_type.field
            foreign_rtype = field_type.rtype

            if hasattr(field_type, 'local_field'):
                local_field = field_type.local_field

            param = FilterRel(foreign_field, foreign_filter, foreign_rtype,
                              local_field, field, oper, val)
        except AttributeError:
            raise InvalidQueryParams(**{
                'detail': 'The filter query param "%s" specified a filter '
                          'containing a "." indicating a relationship filter '
                          'but a relationship by that name does not exist '
                          'on the requested resource.' % key,
                'links': LINK,
                'parameter': PARAM,
            })
        except ValueError:
            param = Filter(field, oper, val)

        _validate_param(param)
        _validate_rel(param, rels)
        _validate_field(param, fields)
        params.append(param)

    return params
195637
def _create_related(self, obj, related, subfield_dict):
        
        for field, items in related.items():
            subobjects = []
            all_subrelated = []
            Subtype, reverse_id_field, subsubdict = subfield_dict[field]
            for order, item in enumerate(items):
                # pull off 'subrelated' (things that are related to this obj)
                subrelated = {}
                for subfield in subsubdict:
                    subrelated[subfield] = item.pop(subfield)

                if field in self.preserve_order:
                    item['order'] = order

                item[reverse_id_field] = obj.id

                try:
                    subobjects.append(Subtype(**item))
                    all_subrelated.append(subrelated)
                except Exception as e:
                    raise DataImportError('{} while importing {} as {}'.format(e, item, Subtype))

            # add all subobjects at once (really great for actions & votes)
            try:
                Subtype.objects.bulk_create(subobjects)
            except Exception as e:
                raise DataImportError('{} while importing {} as {}'.format(e, subobjects, Subtype))

            # after import the subobjects, import their subsubobjects
            for subobj, subrel in zip(subobjects, all_subrelated):
                self._create_related(subobj, subrel, subsubdict)
41747
protected function setConnectedRelationOptions()
    {
        $foreignKey = $this->defaultOptions['foreign_key'];

        if (! $this->db->isTableExists($table = $this->defaultOptions['pivot_table'])) {
            $table = $this->options['pivot_table'] = $this->command->choice(
                "Can't find table {$this->text['pivot_table']} as {$this->text['pivot_text']}, what are you using?",
                $this->getTables()
            );

            $this->text['pivot_table'] = "[".$this->command->paintString($table, 'green')."]";
            $name = Str::singular($table);
            $foreignKey = $name.'_id';
        }

        if (! $this->db->isFieldExists($table, $foreignKey)) {
            $this->options['foreign_key'] = $this->command->choice(
                "Can't find field {$this->text['foreign_key']} in the table {$this->text['pivot_table']} as {$this->text['foreign_text']} of table {$this->text['to_table']}, choice one!",
                $this->getFields($table)
            );
        }

        if (! $this->db->isFieldExists($table, $this->defaultOptions['related_key'])) {
            $this->options['related_key'] = $this->command->choice(
                "Can't find field {$this->text['related_key']} in the table {$this->text['pivot_table']} as {$this->text['related_text']} of table {$this->text['table']}, choice one!",
                $this->getFields($table)
            );
        }
    }
80677
private void addForeignkeys(CollectionDescriptorDef collDef, TableDef tableDef)
    {
        if (!collDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_DATABASE_FOREIGNKEY, true))
        {
            // we shall not generate a database foreignkey
            return;
        }

        // a foreignkey is added to the table schema if for both ends of the collection
        // a table exists
        // then the foreignkey consists of:
        //   remote table  = table of collection owner
        //   local fields  = foreignkey fields in the element type 
        //   remote fields = primarykeys of the collection owner type
        ClassDescriptorDef ownerClassDef    = (ClassDescriptorDef)collDef.getOwner();
        String             elementClassName = collDef.getProperty(PropertyHelper.OJB_PROPERTY_ELEMENT_CLASS_REF);
        ClassDescriptorDef elementClassDef  = ((ModelDef)ownerClassDef.getOwner()).getClass(elementClassName);

        // we can only generate foreignkeys if the collection itself is not shared by
        // several classes in the hierarchy
        for (Iterator it = ownerClassDef.getAllBaseTypes(); it.hasNext();)
        {
            if (containsCollectionAndMapsToDifferentTable(collDef, tableDef, (ClassDescriptorDef)it.next()))
            {
                return;
            }
        }
        for (Iterator it = ownerClassDef.getAllExtentClasses(); it.hasNext();)
        {
            if (containsCollectionAndMapsToDifferentTable(collDef, tableDef, (ClassDescriptorDef)it.next()))
            {
                return;
            }
        }

        // We add a foreignkey to all classes in the subtype hierarchy of the element type
        // that map to a table (we're silently assuming that they contain the fk fields) 
        ArrayList candidates = new ArrayList();

        if (elementClassDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))
        {
            candidates.add(elementClassDef);
        }
        for (Iterator it = elementClassDef.getAllExtentClasses(); it.hasNext();)
        {
            ClassDescriptorDef curSubTypeDef = (ClassDescriptorDef)it.next();

            if (curSubTypeDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true))
            {
                candidates.add(curSubTypeDef);
            }
        }

        String    name            = collDef.getName();
        ArrayList remoteFields    = ownerClassDef.getPrimaryKeys();
        HashMap   processedTables = new HashMap();

        for (Iterator it = candidates.iterator(); it.hasNext();)
        {
            elementClassDef = (ClassDescriptorDef)it.next();
            try
            {
                // for the element class and its subclasses
                String elementTableName = elementClassDef.getProperty(PropertyHelper.OJB_PROPERTY_TABLE);

                // ensure that tables are only processed once
                if (!processedTables.containsKey(elementTableName))
                {
                    ArrayList localFields     = elementClassDef.getFields(collDef.getProperty(PropertyHelper.OJB_PROPERTY_FOREIGNKEY));
                    TableDef  elementTableDef = getTable(elementTableName);
    
                    if (elementTableDef == null)
                    {
                        elementTableDef = new TableDef(elementTableName);
                        addTable(elementTableDef);
                    }
                    elementTableDef.addForeignkey(name, tableDef.getName(), getColumns(localFields), getColumns(remoteFields));
                    processedTables.put(elementTableName, null);
                }
            }
            catch (NoSuchFieldException ex)
            {
                // Shouldn't happen, but even if, then we're ignoring it and simply don't add the fk
            }
        }
    }
352345
def create(pid_type, pid_value, status, object_type, object_uuid):
    """"""
    from .models import PersistentIdentifier

    if bool(object_type) ^ bool(object_uuid):
        raise click.BadParameter('Speficy both or any of --type and --uuid.')

    new_pid = PersistentIdentifier.create(
        pid_type,
        pid_value,
        status=status,
        object_type=object_type,
        object_uuid=object_uuid,
    )
    db.session.commit()
    click.echo(
        '{0.pid_type} {0.pid_value} {0.pid_provider}'.format(new_pid)
    )
192825
public function linkTo($key, $model, $foreign): void
    {
        Relations::setRelation($this->model, $key, $model, $foreign);
    }
551143
def SetModel( self, model, adapter=None ):
        """"""
        self.model = model
        if adapter is not None:
            self.adapter = adapter
        self.UpdateDrawing()
392454
def set_model(self, model):
        
        self._model = model

        self._query.from_(model.get_table())

        return self
234421
def create(self, fields):
        
        try:
            # Cleaning the fields, and check if has `ForeignKey` type.
            cleaned_fields = {}
            for key, value in fields.items():
                if type(value) is dict:
                    try:
                        if value['type'] == 'fk':
                            fake_fk = self.fake_fk(value['field_name'])
                            cleaned_fields.update({key: fake_fk})
                    except:
                        pass
                else:
                    cleaned_fields.update({key: value})

            # Creating the object from dictionary fields.
            model_class = self.model_class()
            obj = model_class.objects.create(**cleaned_fields)

            # The `ManyToManyField` need specific object,
            # so i handle it after created the object.
            for key, value in fields.items():
                if type(value) is dict:
                    try:
                        if value['type'] == 'm2m':
                            self.fake_m2m(obj, value['field_name'])
                    except:
                        pass
            try:
                obj.save_m2m()
            except:
                obj.save()
            return obj
        except Exception as e:
            raise e
410513
def _attach_to_model(self, model):
        
        super(RelatedFieldMixin, self)._attach_to_model(model)

        if model.abstract:
            # do not manage the relation if it's an abstract model
            return

        # now, check related_name and save the relation in the database

        # get related parameters to identify the relation
        self.related_name = self._get_related_name()
        self.related_to = self._get_related_model_name()

        # create entry for the model in the _relations list of the database
        if not hasattr(self.database, '_relations'):
            self.database._relations = {}
        self.database._relations.setdefault(self.related_to, [])

        # check unicity of related name for related model
        self._assert_relation_does_not_exists()

        # the relation didn't exists, we can save it
        relation = (self._model._name, self.name, self.related_name)
        self.database._relations[self.related_to].append(relation)
1262656
function MorphMany(model, related, id, type, localKey) {
        var _this = _super.call(this, model) /* istanbul ignore next */ || this;
        _this.related = _this.model.relation(related);
        _this.id = id;
        _this.type = type;
        _this.localKey = localKey;
        return _this;
    }
432686
def _create_id_field(new_class):
        """"""
        id_field = Auto(identifier=True)

        setattr(new_class, 'id', id_field)
        id_field.__set_name__(new_class, 'id')

        # Ensure ID field is updated properly in Meta attribute
        new_class.meta_.declared_fields['id'] = id_field
        new_class.meta_.id_field = id_field
1123172
public void setRelationId(String relationId) {

        try {
            m_relationId = new CmsUUID(relationId);
        } catch (Throwable e) {
            setThrowable(e);
        }
    }
182397
public void addForeignKeyField(int newId)
    {
        if (m_ForeignKeyFields == null)
        {
            m_ForeignKeyFields = new Vector();
        }
        m_ForeignKeyFields.add(new Integer(newId));
    }