diff --git a/embedded_struct_test.go b/embedded_struct_test.go index 7be75d99..89938bc6 100644 --- a/embedded_struct_test.go +++ b/embedded_struct_test.go @@ -8,16 +8,34 @@ type BasePost struct { URL string } +type Author struct { + Name string + Email string +} + type HNPost struct { BasePost + Author `gorm:"embedded_prefix:user_"` // Embedded struct Upvotes int32 } type EngadgetPost struct { BasePost BasePost `gorm:"embedded"` + Author Author `gorm:"embedded;embedded_prefix:author_"` // Embedded struct ImageUrl string } +func TestPrefixColumnNameForEmbeddedStruct(t *testing.T) { + dialect := DB.NewScope(&EngadgetPost{}).Dialect() + if !dialect.HasColumn(DB.NewScope(&EngadgetPost{}).TableName(), "author_name") || !dialect.HasColumn(DB.NewScope(&EngadgetPost{}).TableName(), "author_email") { + t.Errorf("should has prefix for embedded columns") + } + + if !dialect.HasColumn(DB.NewScope(&HNPost{}).TableName(), "user_name") || !dialect.HasColumn(DB.NewScope(&HNPost{}).TableName(), "user_email") { + t.Errorf("should has prefix for embedded columns") + } +} + func TestSaveAndQueryEmbeddedStruct(t *testing.T) { DB.Save(&HNPost{BasePost: BasePost{Title: "news"}}) DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}}) diff --git a/migration_test.go b/migration_test.go index 30085263..08633283 100644 --- a/migration_test.go +++ b/migration_test.go @@ -256,7 +256,6 @@ func runMigration() { for _, value := range values { DB.DropTable(value) } - if err := DB.AutoMigrate(values...).Error; err != nil { panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) } diff --git a/model_struct.go b/model_struct.go index d9e84c3c..8179a1f3 100644 --- a/model_struct.go +++ b/model_struct.go @@ -203,6 +203,9 @@ func (scope *Scope) GetModelStruct() *ModelStruct { for _, subField := range scope.New(fieldValue).GetStructFields() { subField = subField.clone() subField.Names = append([]string{fieldStruct.Name}, subField.Names...) + if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok { + subField.DBName = prefix + subField.DBName + } if subField.IsPrimaryKey { modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField) }