Closed smk1992 closed 4 months ago
If you want to use custom model types, your struct type needs to match the table name.
One way to fix your code is to use generated model types:
var result []model.Categories
If you want to use custom model types, your struct type needs to match the table name. One way to fix your code is to use generated model types:
var result []model.Categories
Category is model generated model type. I like to import tables & models with .
. So I have the model name as singlular while table as plural. I have the updated the code to have it be table.Categories
& model.Category
to avoid confusion.
EDIT: I think I figured out the problem.... Thank you @houten11. Didn't realize renaming the model generated type would break the scanning.
But I am curious, how are we suppose to implement model type renaming for scanning to work? 🤔
This is my generator
postgres.Generate("./internal/db/.",
postgres.DBConnection{
Host: settings.DatabaseHost(),
Port: 5432,
User: settings.DatabaseUsername(),
Password: settings.DatabasePassword(),
DBName: settings.DatabaseName(),
SchemaName: "public",
SslMode: "disable",
},
template.Default(postgres2.Dialect).
UseSchema(func(schema metadata.Schema) template.Schema {
return template.DefaultSchema(schema).
UseModel(template.DefaultModel().
UseTable(func(table metadata.Table) template.TableModel {
if table.Name == "z_migrations" {
return template.TableModel{Skip: true}
}
return template.DefaultTableModel(table).
UseFileName(schema.Name + "_" + table.Name).
UseTypeName(utils.Titleize(table.Name)).
UseField(func(column metadata.Column) template.TableModelField {
defaultTableModelField := template.DefaultTableModelField(column)
if schema.Name == "public" &&
table.Name == "clients" &&
column.Name == "phone_numbers" {
defaultTableModelField.Type = template.NewType(dbtypes.PhoneNumbersJSONB{})
}
switch defaultTableModelField.Type.Name {
case "uuid":
defaultTableModelField.Type = template.NewType(uuid.UUID{})
case "*string":
defaultTableModelField.Type = template.NewType(sql.NullString{})
case "*int32":
defaultTableModelField.Type = template.NewType(sql.NullInt32{})
case "*int64":
defaultTableModelField.Type = template.NewType(sql.NullInt64{})
case "*bool":
defaultTableModelField.Type = template.NewType(sql.NullBool{})
case "*float64":
defaultTableModelField.Type = template.NewType(sql.NullFloat64{})
case "*time.Time":
defaultTableModelField.Type = template.NewType(sql.NullTime{})
}
return defaultTableModelField
})
}),
)
}),
)
If you renamed model type, you can customize SQL Builder default alias:
Sweet thanks that helps a lot
Describe the bug I'm not sure if I'm doing something wrong but I'm running into an issue with the results not mapping to struct.
Environment (please complete the following information):
Code snippet
Output:
Expected behavior Query Results should map to struct