[GORM][GO] Has many slice of many implementations

Viewed 76

I need to register a set of entities which implement the same interface, but they must be registered in different tables as they have different structures.
I am looking for behavior similar to that achieved with jpa: Hibernate Inheritance Mapping

The following example is simplified.

type Person struct {
    ID         uint64 `gorm:"primarykey"`
    Name       string
    Identifier []identificable
}

type identificable interface {
    GetValue() string
}

type DNI struct {
    ID       uint64 `gorm:"primarykey"`
    Value    string
    PersonID uint64
}

func (dni DNI) GetValue() string {
    return dni.Value
}

type DrivingLicense struct {
    ID       uint64 `gorm:"primarykey"`
    Value    string
    PersonID uint64
}

func (licence DrivingLicense) GetValue() string {
    return licence.Value
}

func main() {
    db := getDB()
    dni1 := DNI{}
    dni1.Value = "testdni1"
    drivingLicense1 := DrivingLicense{}
    dni1.Value = "License1"

    person := Person{}
    person.Name = "test_name"
    person.Identifier = []identificable{dni1, drivingLicense1}

    result := db.Create(&person)
    if result.Error != nil {
        fmt.Sprintf(result.Error.Error())
    }
}
1 Answers

GORM derives table names from the structure name, it has nothing to with interfaces.

Each of the structures will be put in their own table.

Please provide more code and details about exactly where you are running into a problem.

Related