Support set prefix for embedded struct

This commit is contained in:
Jinzhu 2016-09-05 22:26:57 +08:00
parent f26fa242cc
commit 446ce99a42
3 changed files with 21 additions and 1 deletions

View File

@ -8,16 +8,34 @@ type BasePost struct {
URL string URL string
} }
type Author struct {
Name string
Email string
}
type HNPost struct { type HNPost struct {
BasePost BasePost
Author `gorm:"embedded_prefix:user_"` // Embedded struct
Upvotes int32 Upvotes int32
} }
type EngadgetPost struct { type EngadgetPost struct {
BasePost BasePost `gorm:"embedded"` BasePost BasePost `gorm:"embedded"`
Author Author `gorm:"embedded;embedded_prefix:author_"` // Embedded struct
ImageUrl string 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) { func TestSaveAndQueryEmbeddedStruct(t *testing.T) {
DB.Save(&HNPost{BasePost: BasePost{Title: "news"}}) DB.Save(&HNPost{BasePost: BasePost{Title: "news"}})
DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}}) DB.Save(&HNPost{BasePost: BasePost{Title: "hn_news"}})

View File

@ -256,7 +256,6 @@ func runMigration() {
for _, value := range values { for _, value := range values {
DB.DropTable(value) DB.DropTable(value)
} }
if err := DB.AutoMigrate(values...).Error; err != nil { if err := DB.AutoMigrate(values...).Error; err != nil {
panic(fmt.Sprintf("No error should happen when create table, but got %+v", err)) panic(fmt.Sprintf("No error should happen when create table, but got %+v", err))
} }

View File

@ -203,6 +203,9 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
for _, subField := range scope.New(fieldValue).GetStructFields() { for _, subField := range scope.New(fieldValue).GetStructFields() {
subField = subField.clone() subField = subField.clone()
subField.Names = append([]string{fieldStruct.Name}, subField.Names...) subField.Names = append([]string{fieldStruct.Name}, subField.Names...)
if prefix, ok := field.TagSettings["EMBEDDED_PREFIX"]; ok {
subField.DBName = prefix + subField.DBName
}
if subField.IsPrimaryKey { if subField.IsPrimaryKey {
modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField) modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
} }