MCPcopy
hub / github.com/go-gorm/gorm / parseRelation

Method parseRelation

schema/relationship.go:65–131  ·  view source on GitHub ↗
(field *Field)

Source from the content-addressed store, hash-verified

63}
64
65func (schema *Schema) parseRelation(field *Field) *Relationship {
66 var (
67 err error
68 fieldValue = reflect.New(field.IndirectFieldType).Interface()
69 relation = &Relationship{
70 Name: field.Name,
71 Field: field,
72 Schema: schema,
73 foreignKeys: toColumns(field.TagSettings["FOREIGNKEY"]),
74 primaryKeys: toColumns(field.TagSettings["REFERENCES"]),
75 }
76 )
77
78 if relation.FieldSchema, err = getOrParse(fieldValue, schema.cacheStore, schema.namer); err != nil {
79 schema.err = fmt.Errorf("failed to parse field: %s, error: %w", field.Name, err)
80 return nil
81 }
82
83 if hasPolymorphicRelation(field.TagSettings) {
84 schema.buildPolymorphicRelation(relation, field)
85 } else if many2many := field.TagSettings["MANY2MANY"]; many2many != "" {
86 schema.buildMany2ManyRelation(relation, field, many2many)
87 } else if belongsTo := field.TagSettings["BELONGSTO"]; belongsTo != "" {
88 schema.guessRelation(relation, field, guessBelongs)
89 } else {
90 switch field.IndirectFieldType.Kind() {
91 case reflect.Struct:
92 schema.guessRelation(relation, field, guessGuess)
93 case reflect.Slice:
94 schema.guessRelation(relation, field, guessHas)
95 default:
96 schema.err = fmt.Errorf("unsupported data type %v for %v on field %s", relation.FieldSchema, schema,
97 field.Name)
98 }
99 }
100
101 if relation.Type == has {
102 if relation.FieldSchema != relation.Schema && relation.Polymorphic == nil && field.OwnerSchema == nil {
103 relation.FieldSchema.Relationships.Mux.Lock()
104 relation.FieldSchema.Relationships.Relations["_"+relation.Schema.Name+"_"+relation.Name] = relation
105 relation.FieldSchema.Relationships.Mux.Unlock()
106 }
107
108 switch field.IndirectFieldType.Kind() {
109 case reflect.Struct:
110 relation.Type = HasOne
111 case reflect.Slice:
112 relation.Type = HasMany
113 }
114 }
115
116 if schema.err == nil {
117 schema.setRelation(relation)
118 switch relation.Type {
119 case HasOne:
120 schema.Relationships.HasOne = append(schema.Relationships.HasOne, relation)
121 case HasMany:
122 schema.Relationships.HasMany = append(schema.Relationships.HasMany, relation)

Callers 1

Calls 8

guessRelationMethod · 0.95
setRelationMethod · 0.95
toColumnsFunction · 0.85
getOrParseFunction · 0.85
hasPolymorphicRelationFunction · 0.85
NewMethod · 0.65

Tested by

no test coverage detected