mirror of https://github.com/go-gorm/gorm.git
Support set prefix for embedded struct
This commit is contained in:
parent
f26fa242cc
commit
446ce99a42
|
@ -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"}})
|
||||
|
|
|
@ -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))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue