Your Question
Hello! I want to know if it is possible to create a table with relations from a struct created by reflection
I run into the problem that I can't assign a name to it since it doesn't have a Type.Name
The document you expected this should be explained
Expected answer
example:
struct1Fields := []reflect.StructField{
{
Name: "field1",
Type: reflect.TypeOf("string"),
},
}
struct1 := reflect.StructOf(struct1Fields)
struct2Fields := []reflect.StructField{
{
Name: "struct1",
Type: struct1,
},
}
struct2 := reflect.StructOf(struct2Fields)
DB.AutoMigrate(reflect.New(struct1), reflect.New(struct2))
my problem is when i try to create that "tables" GORM can't get a properly name to it in MySQL so tries to run a malformed query (CREATE TABLE `` (....)
we tried some ways to implement "Tabler" interface with anonymous fields but isn't possible because when schema tries to parse tablename creates a new *struct value and our anonymous field lose Tabler interface implementation
schema.go:123
modelValue := reflect.New(modelType)
tableName := namer.TableName(modelType.Name())
if tabler, ok := modelValue.Interface().(Tabler); ok {
tableName = tabler.TableName()
}
if en, ok := namer.(embeddedNamer); ok {
tableName = en.Table
}
if specialTableName != "" && specialTableName != tableName {
tableName = specialTableName
}
any idea about how can we solve it? is possible to implement a new Namer strategy with modelType as parameter?
like this:
tableName := namer.TableName(modelType.Name())
tableName = namer.TableNameFromType(modelType)
Comment From: li-jin-gou
refer to https://gorm.cn/docs/conventions.html#TableName
Comment From: simlecode
refer to https://gorm.io/docs/conventions.html#TableName