model_struct.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. package gorm
  2. import (
  3. "database/sql"
  4. "errors"
  5. "go/ast"
  6. "reflect"
  7. "strings"
  8. "sync"
  9. "time"
  10. "github.com/jinzhu/inflection"
  11. )
  12. // DefaultTableNameHandler default table name handler
  13. var DefaultTableNameHandler = func(db *DB, defaultTableName string) string {
  14. return defaultTableName
  15. }
  16. type safeModelStructsMap struct {
  17. m map[reflect.Type]*ModelStruct
  18. l *sync.RWMutex
  19. }
  20. func (s *safeModelStructsMap) Set(key reflect.Type, value *ModelStruct) {
  21. s.l.Lock()
  22. defer s.l.Unlock()
  23. s.m[key] = value
  24. }
  25. func (s *safeModelStructsMap) Get(key reflect.Type) *ModelStruct {
  26. s.l.RLock()
  27. defer s.l.RUnlock()
  28. return s.m[key]
  29. }
  30. func newModelStructsMap() *safeModelStructsMap {
  31. return &safeModelStructsMap{l: new(sync.RWMutex), m: make(map[reflect.Type]*ModelStruct)}
  32. }
  33. var modelStructsMap = newModelStructsMap()
  34. // ModelStruct model definition
  35. type ModelStruct struct {
  36. PrimaryFields []*StructField
  37. StructFields []*StructField
  38. ModelType reflect.Type
  39. defaultTableName string
  40. }
  41. // TableName get model's table name
  42. func (s *ModelStruct) TableName(db *DB) string {
  43. if s.defaultTableName == "" && db != nil && s.ModelType != nil {
  44. // Set default table name
  45. if tabler, ok := reflect.New(s.ModelType).Interface().(tabler); ok {
  46. s.defaultTableName = tabler.TableName()
  47. } else {
  48. tableName := ToDBName(s.ModelType.Name())
  49. if db == nil || !db.parent.singularTable {
  50. tableName = inflection.Plural(tableName)
  51. }
  52. s.defaultTableName = tableName
  53. }
  54. }
  55. return DefaultTableNameHandler(db, s.defaultTableName)
  56. }
  57. // StructField model field's struct definition
  58. type StructField struct {
  59. DBName string
  60. Name string
  61. Names []string
  62. IsPrimaryKey bool
  63. IsNormal bool
  64. IsIgnored bool
  65. IsScanner bool
  66. HasDefaultValue bool
  67. Tag reflect.StructTag
  68. TagSettings map[string]string
  69. Struct reflect.StructField
  70. IsForeignKey bool
  71. Relationship *Relationship
  72. }
  73. func (structField *StructField) clone() *StructField {
  74. clone := &StructField{
  75. DBName: structField.DBName,
  76. Name: structField.Name,
  77. Names: structField.Names,
  78. IsPrimaryKey: structField.IsPrimaryKey,
  79. IsNormal: structField.IsNormal,
  80. IsIgnored: structField.IsIgnored,
  81. IsScanner: structField.IsScanner,
  82. HasDefaultValue: structField.HasDefaultValue,
  83. Tag: structField.Tag,
  84. TagSettings: map[string]string{},
  85. Struct: structField.Struct,
  86. IsForeignKey: structField.IsForeignKey,
  87. }
  88. if structField.Relationship != nil {
  89. relationship := *structField.Relationship
  90. clone.Relationship = &relationship
  91. }
  92. for key, value := range structField.TagSettings {
  93. clone.TagSettings[key] = value
  94. }
  95. return clone
  96. }
  97. // Relationship described the relationship between models
  98. type Relationship struct {
  99. Kind string
  100. PolymorphicType string
  101. PolymorphicDBName string
  102. PolymorphicValue string
  103. ForeignFieldNames []string
  104. ForeignDBNames []string
  105. AssociationForeignFieldNames []string
  106. AssociationForeignDBNames []string
  107. JoinTableHandler JoinTableHandlerInterface
  108. }
  109. func getForeignField(column string, fields []*StructField) *StructField {
  110. for _, field := range fields {
  111. if field.Name == column || field.DBName == column || field.DBName == ToDBName(column) {
  112. return field
  113. }
  114. }
  115. return nil
  116. }
  117. // GetModelStruct get value's model struct, relationships based on struct and tag definition
  118. func (scope *Scope) GetModelStruct() *ModelStruct {
  119. var modelStruct ModelStruct
  120. // Scope value can't be nil
  121. if scope.Value == nil {
  122. return &modelStruct
  123. }
  124. reflectType := reflect.ValueOf(scope.Value).Type()
  125. for reflectType.Kind() == reflect.Slice || reflectType.Kind() == reflect.Ptr {
  126. reflectType = reflectType.Elem()
  127. }
  128. // Scope value need to be a struct
  129. if reflectType.Kind() != reflect.Struct {
  130. return &modelStruct
  131. }
  132. // Get Cached model struct
  133. if value := modelStructsMap.Get(reflectType); value != nil {
  134. return value
  135. }
  136. modelStruct.ModelType = reflectType
  137. // Get all fields
  138. for i := 0; i < reflectType.NumField(); i++ {
  139. if fieldStruct := reflectType.Field(i); ast.IsExported(fieldStruct.Name) {
  140. field := &StructField{
  141. Struct: fieldStruct,
  142. Name: fieldStruct.Name,
  143. Names: []string{fieldStruct.Name},
  144. Tag: fieldStruct.Tag,
  145. TagSettings: parseTagSetting(fieldStruct.Tag),
  146. }
  147. // is ignored field
  148. if _, ok := field.TagSettings["-"]; ok {
  149. field.IsIgnored = true
  150. } else {
  151. if _, ok := field.TagSettings["PRIMARY_KEY"]; ok {
  152. field.IsPrimaryKey = true
  153. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
  154. }
  155. if _, ok := field.TagSettings["DEFAULT"]; ok {
  156. field.HasDefaultValue = true
  157. }
  158. if _, ok := field.TagSettings["AUTO_INCREMENT"]; ok && !field.IsPrimaryKey {
  159. field.HasDefaultValue = true
  160. }
  161. indirectType := fieldStruct.Type
  162. for indirectType.Kind() == reflect.Ptr {
  163. indirectType = indirectType.Elem()
  164. }
  165. fieldValue := reflect.New(indirectType).Interface()
  166. if _, isScanner := fieldValue.(sql.Scanner); isScanner {
  167. // is scanner
  168. field.IsScanner, field.IsNormal = true, true
  169. if indirectType.Kind() == reflect.Struct {
  170. for i := 0; i < indirectType.NumField(); i++ {
  171. for key, value := range parseTagSetting(indirectType.Field(i).Tag) {
  172. if _, ok := field.TagSettings[key]; !ok {
  173. field.TagSettings[key] = value
  174. }
  175. }
  176. }
  177. }
  178. } else if _, isTime := fieldValue.(*time.Time); isTime {
  179. // is time
  180. field.IsNormal = true
  181. } else if _, ok := field.TagSettings["EMBEDDED"]; ok || fieldStruct.Anonymous {
  182. // is embedded struct
  183. for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields {
  184. subField = subField.clone()
  185. subField.Names = append([]string{fieldStruct.Name}, subField.Names...)
  186. if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok {
  187. subField.DBName = prefix + subField.DBName
  188. }
  189. if subField.IsPrimaryKey {
  190. if _, ok := subField.TagSettings["PRIMARY_KEY"]; ok {
  191. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
  192. } else {
  193. subField.IsPrimaryKey = false
  194. }
  195. }
  196. if subField.Relationship != nil && subField.Relationship.JoinTableHandler != nil {
  197. if joinTableHandler, ok := subField.Relationship.JoinTableHandler.(*JoinTableHandler); ok {
  198. newJoinTableHandler := &JoinTableHandler{}
  199. newJoinTableHandler.Setup(subField.Relationship, joinTableHandler.TableName, reflectType, joinTableHandler.Destination.ModelType)
  200. subField.Relationship.JoinTableHandler = newJoinTableHandler
  201. }
  202. }
  203. modelStruct.StructFields = append(modelStruct.StructFields, subField)
  204. }
  205. continue
  206. } else {
  207. // build relationships
  208. switch indirectType.Kind() {
  209. case reflect.Slice:
  210. defer func(field *StructField) {
  211. var (
  212. relationship = &Relationship{}
  213. toScope = scope.New(reflect.New(field.Struct.Type).Interface())
  214. foreignKeys []string
  215. associationForeignKeys []string
  216. elemType = field.Struct.Type
  217. )
  218. if foreignKey := field.TagSettings["FOREIGNKEY"]; foreignKey != "" {
  219. foreignKeys = strings.Split(foreignKey, ",")
  220. }
  221. if foreignKey := field.TagSettings["ASSOCIATION_FOREIGNKEY"]; foreignKey != "" {
  222. associationForeignKeys = strings.Split(foreignKey, ",")
  223. } else if foreignKey := field.TagSettings["ASSOCIATIONFOREIGNKEY"]; foreignKey != "" {
  224. associationForeignKeys = strings.Split(foreignKey, ",")
  225. }
  226. for elemType.Kind() == reflect.Slice || elemType.Kind() == reflect.Ptr {
  227. elemType = elemType.Elem()
  228. }
  229. if elemType.Kind() == reflect.Struct {
  230. if many2many := field.TagSettings["MANY2MANY"]; many2many != "" {
  231. relationship.Kind = "many_to_many"
  232. { // Foreign Keys for Source
  233. joinTableDBNames := []string{}
  234. if foreignKey := field.TagSettings["JOINTABLE_FOREIGNKEY"]; foreignKey != "" {
  235. joinTableDBNames = strings.Split(foreignKey, ",")
  236. }
  237. // if no foreign keys defined with tag
  238. if len(foreignKeys) == 0 {
  239. for _, field := range modelStruct.PrimaryFields {
  240. foreignKeys = append(foreignKeys, field.DBName)
  241. }
  242. }
  243. for idx, foreignKey := range foreignKeys {
  244. if foreignField := getForeignField(foreignKey, modelStruct.StructFields); foreignField != nil {
  245. // source foreign keys (db names)
  246. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.DBName)
  247. // setup join table foreign keys for source
  248. if len(joinTableDBNames) > idx {
  249. // if defined join table's foreign key
  250. relationship.ForeignDBNames = append(relationship.ForeignDBNames, joinTableDBNames[idx])
  251. } else {
  252. defaultJointableForeignKey := ToDBName(reflectType.Name()) + "_" + foreignField.DBName
  253. relationship.ForeignDBNames = append(relationship.ForeignDBNames, defaultJointableForeignKey)
  254. }
  255. }
  256. }
  257. }
  258. { // Foreign Keys for Association (Destination)
  259. associationJoinTableDBNames := []string{}
  260. if foreignKey := field.TagSettings["ASSOCIATION_JOINTABLE_FOREIGNKEY"]; foreignKey != "" {
  261. associationJoinTableDBNames = strings.Split(foreignKey, ",")
  262. }
  263. // if no association foreign keys defined with tag
  264. if len(associationForeignKeys) == 0 {
  265. for _, field := range toScope.PrimaryFields() {
  266. associationForeignKeys = append(associationForeignKeys, field.DBName)
  267. }
  268. }
  269. for idx, name := range associationForeignKeys {
  270. if field, ok := toScope.FieldByName(name); ok {
  271. // association foreign keys (db names)
  272. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, field.DBName)
  273. // setup join table foreign keys for association
  274. if len(associationJoinTableDBNames) > idx {
  275. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationJoinTableDBNames[idx])
  276. } else {
  277. // join table foreign keys for association
  278. joinTableDBName := ToDBName(elemType.Name()) + "_" + field.DBName
  279. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, joinTableDBName)
  280. }
  281. }
  282. }
  283. }
  284. joinTableHandler := JoinTableHandler{}
  285. joinTableHandler.Setup(relationship, many2many, reflectType, elemType)
  286. relationship.JoinTableHandler = &joinTableHandler
  287. field.Relationship = relationship
  288. } else {
  289. // User has many comments, associationType is User, comment use UserID as foreign key
  290. var associationType = reflectType.Name()
  291. var toFields = toScope.GetStructFields()
  292. relationship.Kind = "has_many"
  293. if polymorphic := field.TagSettings["POLYMORPHIC"]; polymorphic != "" {
  294. // Dog has many toys, tag polymorphic is Owner, then associationType is Owner
  295. // Toy use OwnerID, OwnerType ('dogs') as foreign key
  296. if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil {
  297. associationType = polymorphic
  298. relationship.PolymorphicType = polymorphicType.Name
  299. relationship.PolymorphicDBName = polymorphicType.DBName
  300. // if Dog has multiple set of toys set name of the set (instead of default 'dogs')
  301. if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok {
  302. relationship.PolymorphicValue = value
  303. } else {
  304. relationship.PolymorphicValue = scope.TableName()
  305. }
  306. polymorphicType.IsForeignKey = true
  307. }
  308. }
  309. // if no foreign keys defined with tag
  310. if len(foreignKeys) == 0 {
  311. // if no association foreign keys defined with tag
  312. if len(associationForeignKeys) == 0 {
  313. for _, field := range modelStruct.PrimaryFields {
  314. foreignKeys = append(foreignKeys, associationType+field.Name)
  315. associationForeignKeys = append(associationForeignKeys, field.Name)
  316. }
  317. } else {
  318. // generate foreign keys from defined association foreign keys
  319. for _, scopeFieldName := range associationForeignKeys {
  320. if foreignField := getForeignField(scopeFieldName, modelStruct.StructFields); foreignField != nil {
  321. foreignKeys = append(foreignKeys, associationType+foreignField.Name)
  322. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  323. }
  324. }
  325. }
  326. } else {
  327. // generate association foreign keys from foreign keys
  328. if len(associationForeignKeys) == 0 {
  329. for _, foreignKey := range foreignKeys {
  330. if strings.HasPrefix(foreignKey, associationType) {
  331. associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
  332. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  333. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  334. }
  335. }
  336. }
  337. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  338. associationForeignKeys = []string{scope.PrimaryKey()}
  339. }
  340. } else if len(foreignKeys) != len(associationForeignKeys) {
  341. scope.Err(errors.New("invalid foreign keys, should have same length"))
  342. return
  343. }
  344. }
  345. for idx, foreignKey := range foreignKeys {
  346. if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
  347. if associationField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); associationField != nil {
  348. // source foreign keys
  349. foreignField.IsForeignKey = true
  350. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
  351. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationField.DBName)
  352. // association foreign keys
  353. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  354. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  355. }
  356. }
  357. }
  358. if len(relationship.ForeignFieldNames) != 0 {
  359. field.Relationship = relationship
  360. }
  361. }
  362. } else {
  363. field.IsNormal = true
  364. }
  365. }(field)
  366. case reflect.Struct:
  367. defer func(field *StructField) {
  368. var (
  369. // user has one profile, associationType is User, profile use UserID as foreign key
  370. // user belongs to profile, associationType is Profile, user use ProfileID as foreign key
  371. associationType = reflectType.Name()
  372. relationship = &Relationship{}
  373. toScope = scope.New(reflect.New(field.Struct.Type).Interface())
  374. toFields = toScope.GetStructFields()
  375. tagForeignKeys []string
  376. tagAssociationForeignKeys []string
  377. )
  378. if foreignKey := field.TagSettings["FOREIGNKEY"]; foreignKey != "" {
  379. tagForeignKeys = strings.Split(foreignKey, ",")
  380. }
  381. if foreignKey := field.TagSettings["ASSOCIATION_FOREIGNKEY"]; foreignKey != "" {
  382. tagAssociationForeignKeys = strings.Split(foreignKey, ",")
  383. } else if foreignKey := field.TagSettings["ASSOCIATIONFOREIGNKEY"]; foreignKey != "" {
  384. tagAssociationForeignKeys = strings.Split(foreignKey, ",")
  385. }
  386. if polymorphic := field.TagSettings["POLYMORPHIC"]; polymorphic != "" {
  387. // Cat has one toy, tag polymorphic is Owner, then associationType is Owner
  388. // Toy use OwnerID, OwnerType ('cats') as foreign key
  389. if polymorphicType := getForeignField(polymorphic+"Type", toFields); polymorphicType != nil {
  390. associationType = polymorphic
  391. relationship.PolymorphicType = polymorphicType.Name
  392. relationship.PolymorphicDBName = polymorphicType.DBName
  393. // if Cat has several different types of toys set name for each (instead of default 'cats')
  394. if value, ok := field.TagSettings["POLYMORPHIC_VALUE"]; ok {
  395. relationship.PolymorphicValue = value
  396. } else {
  397. relationship.PolymorphicValue = scope.TableName()
  398. }
  399. polymorphicType.IsForeignKey = true
  400. }
  401. }
  402. // Has One
  403. {
  404. var foreignKeys = tagForeignKeys
  405. var associationForeignKeys = tagAssociationForeignKeys
  406. // if no foreign keys defined with tag
  407. if len(foreignKeys) == 0 {
  408. // if no association foreign keys defined with tag
  409. if len(associationForeignKeys) == 0 {
  410. for _, primaryField := range modelStruct.PrimaryFields {
  411. foreignKeys = append(foreignKeys, associationType+primaryField.Name)
  412. associationForeignKeys = append(associationForeignKeys, primaryField.Name)
  413. }
  414. } else {
  415. // generate foreign keys form association foreign keys
  416. for _, associationForeignKey := range tagAssociationForeignKeys {
  417. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  418. foreignKeys = append(foreignKeys, associationType+foreignField.Name)
  419. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  420. }
  421. }
  422. }
  423. } else {
  424. // generate association foreign keys from foreign keys
  425. if len(associationForeignKeys) == 0 {
  426. for _, foreignKey := range foreignKeys {
  427. if strings.HasPrefix(foreignKey, associationType) {
  428. associationForeignKey := strings.TrimPrefix(foreignKey, associationType)
  429. if foreignField := getForeignField(associationForeignKey, modelStruct.StructFields); foreignField != nil {
  430. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  431. }
  432. }
  433. }
  434. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  435. associationForeignKeys = []string{scope.PrimaryKey()}
  436. }
  437. } else if len(foreignKeys) != len(associationForeignKeys) {
  438. scope.Err(errors.New("invalid foreign keys, should have same length"))
  439. return
  440. }
  441. }
  442. for idx, foreignKey := range foreignKeys {
  443. if foreignField := getForeignField(foreignKey, toFields); foreignField != nil {
  444. if scopeField := getForeignField(associationForeignKeys[idx], modelStruct.StructFields); scopeField != nil {
  445. foreignField.IsForeignKey = true
  446. // source foreign keys
  447. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, scopeField.Name)
  448. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, scopeField.DBName)
  449. // association foreign keys
  450. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  451. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  452. }
  453. }
  454. }
  455. }
  456. if len(relationship.ForeignFieldNames) != 0 {
  457. relationship.Kind = "has_one"
  458. field.Relationship = relationship
  459. } else {
  460. var foreignKeys = tagForeignKeys
  461. var associationForeignKeys = tagAssociationForeignKeys
  462. if len(foreignKeys) == 0 {
  463. // generate foreign keys & association foreign keys
  464. if len(associationForeignKeys) == 0 {
  465. for _, primaryField := range toScope.PrimaryFields() {
  466. foreignKeys = append(foreignKeys, field.Name+primaryField.Name)
  467. associationForeignKeys = append(associationForeignKeys, primaryField.Name)
  468. }
  469. } else {
  470. // generate foreign keys with association foreign keys
  471. for _, associationForeignKey := range associationForeignKeys {
  472. if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil {
  473. foreignKeys = append(foreignKeys, field.Name+foreignField.Name)
  474. associationForeignKeys = append(associationForeignKeys, foreignField.Name)
  475. }
  476. }
  477. }
  478. } else {
  479. // generate foreign keys & association foreign keys
  480. if len(associationForeignKeys) == 0 {
  481. for _, foreignKey := range foreignKeys {
  482. if strings.HasPrefix(foreignKey, field.Name) {
  483. associationForeignKey := strings.TrimPrefix(foreignKey, field.Name)
  484. if foreignField := getForeignField(associationForeignKey, toFields); foreignField != nil {
  485. associationForeignKeys = append(associationForeignKeys, associationForeignKey)
  486. }
  487. }
  488. }
  489. if len(associationForeignKeys) == 0 && len(foreignKeys) == 1 {
  490. associationForeignKeys = []string{toScope.PrimaryKey()}
  491. }
  492. } else if len(foreignKeys) != len(associationForeignKeys) {
  493. scope.Err(errors.New("invalid foreign keys, should have same length"))
  494. return
  495. }
  496. }
  497. for idx, foreignKey := range foreignKeys {
  498. if foreignField := getForeignField(foreignKey, modelStruct.StructFields); foreignField != nil {
  499. if associationField := getForeignField(associationForeignKeys[idx], toFields); associationField != nil {
  500. foreignField.IsForeignKey = true
  501. // association foreign keys
  502. relationship.AssociationForeignFieldNames = append(relationship.AssociationForeignFieldNames, associationField.Name)
  503. relationship.AssociationForeignDBNames = append(relationship.AssociationForeignDBNames, associationField.DBName)
  504. // source foreign keys
  505. relationship.ForeignFieldNames = append(relationship.ForeignFieldNames, foreignField.Name)
  506. relationship.ForeignDBNames = append(relationship.ForeignDBNames, foreignField.DBName)
  507. }
  508. }
  509. }
  510. if len(relationship.ForeignFieldNames) != 0 {
  511. relationship.Kind = "belongs_to"
  512. field.Relationship = relationship
  513. }
  514. }
  515. }(field)
  516. default:
  517. field.IsNormal = true
  518. }
  519. }
  520. }
  521. // Even it is ignored, also possible to decode db value into the field
  522. if value, ok := field.TagSettings["COLUMN"]; ok {
  523. field.DBName = value
  524. } else {
  525. field.DBName = ToDBName(fieldStruct.Name)
  526. }
  527. modelStruct.StructFields = append(modelStruct.StructFields, field)
  528. }
  529. }
  530. if len(modelStruct.PrimaryFields) == 0 {
  531. if field := getForeignField("id", modelStruct.StructFields); field != nil {
  532. field.IsPrimaryKey = true
  533. modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, field)
  534. }
  535. }
  536. modelStructsMap.Set(reflectType, &modelStruct)
  537. return &modelStruct
  538. }
  539. // GetStructFields get model's field structs
  540. func (scope *Scope) GetStructFields() (fields []*StructField) {
  541. return scope.GetModelStruct().StructFields
  542. }
  543. func parseTagSetting(tags reflect.StructTag) map[string]string {
  544. setting := map[string]string{}
  545. for _, str := range []string{tags.Get("sql"), tags.Get("gorm")} {
  546. tags := strings.Split(str, ";")
  547. for _, value := range tags {
  548. v := strings.Split(value, ":")
  549. k := strings.TrimSpace(strings.ToUpper(v[0]))
  550. if len(v) >= 2 {
  551. setting[k] = strings.Join(v[1:], ":")
  552. } else {
  553. setting[k] = k
  554. }
  555. }
  556. }
  557. return setting
  558. }