diff --git a/embedded_struct_test.go b/embedded_struct_test.go index 89938bc6..91dd0563 100644 --- a/embedded_struct_test.go +++ b/embedded_struct_test.go @@ -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") } } diff --git a/model_struct.go b/model_struct.go index 9a609585..7060d3af 100644 --- a/model_struct.go +++ b/model_struct.go @@ -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) }