mirror of https://github.com/go-gorm/gorm.git
Fix primary key for embedded struct
This commit is contained in:
parent
373207d546
commit
1aa2d4ca89
|
@ -9,6 +9,7 @@ type BasePost struct {
|
|||
}
|
||||
|
||||
type Author struct {
|
||||
ID string
|
||||
Name string
|
||||
Email string
|
||||
}
|
||||
|
@ -27,11 +28,17 @@ type EngadgetPost struct {
|
|||
|
||||
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") {
|
||||
engadgetPostScope := DB.NewScope(&EngadgetPost{})
|
||||
if !dialect.HasColumn(engadgetPostScope.TableName(), "author_id") || !dialect.HasColumn(engadgetPostScope.TableName(), "author_name") || !dialect.HasColumn(engadgetPostScope.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") {
|
||||
if len(engadgetPostScope.PrimaryFields()) != 1 {
|
||||
t.Errorf("should have only one primary field with embedded struct, but got %v", len(engadgetPostScope.PrimaryFields()))
|
||||
}
|
||||
|
||||
hnScope := DB.NewScope(&HNPost{})
|
||||
if !dialect.HasColumn(hnScope.TableName(), "user_id") || !dialect.HasColumn(hnScope.TableName(), "user_name") || !dialect.HasColumn(hnScope.TableName(), "user_email") {
|
||||
t.Errorf("should has prefix for embedded columns")
|
||||
}
|
||||
}
|
||||
|
|
|
@ -201,14 +201,19 @@ func (scope *Scope) GetModelStruct() *ModelStruct {
|
|||
field.IsNormal = true
|
||||
} else if _, ok := field.TagSettings["EMBEDDED"]; ok || fieldStruct.Anonymous {
|
||||
// is embedded struct
|
||||
for _, subField := range scope.New(fieldValue).GetStructFields() {
|
||||
for _, subField := range scope.New(fieldValue).GetModelStruct().StructFields {
|
||||
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)
|
||||
if _, ok := subField.TagSettings["PRIMARY_KEY"]; ok {
|
||||
modelStruct.PrimaryFields = append(modelStruct.PrimaryFields, subField)
|
||||
} else {
|
||||
subField.IsPrimaryKey = false
|
||||
}
|
||||
}
|
||||
modelStruct.StructFields = append(modelStruct.StructFields, subField)
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue