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

Method SetupJoinTable

gorm.go:483–531  ·  view source on GitHub ↗

SetupJoinTable setup join table schema

(model interface{}, field string, joinTable interface{})

Source from the content-addressed store, hash-verified

481
482// SetupJoinTable setup join table schema
483func (db *DB) SetupJoinTable(model interface{}, field string, joinTable interface{}) error {
484 var (
485 tx = db.getInstance()
486 stmt = tx.Statement
487 modelSchema, joinSchema *schema.Schema
488 )
489
490 err := stmt.Parse(model)
491 if err != nil {
492 return err
493 }
494 modelSchema = stmt.Schema
495
496 err = stmt.Parse(joinTable)
497 if err != nil {
498 return err
499 }
500 joinSchema = stmt.Schema
501
502 relation, ok := modelSchema.Relationships.Relations[field]
503 isRelation := ok && relation.JoinTable != nil
504 if !isRelation {
505 return fmt.Errorf("failed to find relation: %s", field)
506 }
507
508 for _, ref := range relation.References {
509 f := joinSchema.LookUpField(ref.ForeignKey.DBName)
510 if f == nil {
511 return fmt.Errorf("missing field %s for join table", ref.ForeignKey.DBName)
512 }
513
514 f.DataType = ref.ForeignKey.DataType
515 f.GORMDataType = ref.ForeignKey.GORMDataType
516 if f.Size == 0 {
517 f.Size = ref.ForeignKey.Size
518 }
519 ref.ForeignKey = f
520 }
521
522 for name, rel := range relation.JoinTable.Relationships.Relations {
523 if _, ok := joinSchema.Relationships.Relations[name]; !ok {
524 rel.Schema = joinSchema
525 joinSchema.Relationships.Relations[name] = rel
526 }
527 }
528 relation.JoinTable = joinSchema
529
530 return nil
531}
532
533// Use use plugin
534func (db *DB) Use(plugin Plugin) error {

Callers 2

TestOverrideJoinTableFunction · 0.80

Calls 3

getInstanceMethod · 0.95
ParseMethod · 0.80
LookUpFieldMethod · 0.80

Tested by 2

TestOverrideJoinTableFunction · 0.64