SetupJoinTable setup join table schema
(model interface{}, field string, joinTable interface{})
| 481 | |
| 482 | // SetupJoinTable setup join table schema |
| 483 | func (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 |
| 534 | func (db *DB) Use(plugin Plugin) error { |