Fix get default value from blank primary field

This commit is contained in:
Jinzhu 2016-06-02 11:06:44 +08:00
parent dca5e54f8b
commit bf0e236078
1 changed files with 13 additions and 9 deletions

View File

@ -50,14 +50,12 @@ func createCallback(scope *Scope) {
for _, field := range scope.Fields() { for _, field := range scope.Fields() {
if scope.changeableField(field) { if scope.changeableField(field) {
if field.IsNormal { if field.IsNormal {
if !field.IsPrimaryKey || !field.IsBlank { if field.IsBlank && field.HasDefaultValue {
if field.IsBlank && field.HasDefaultValue { blankColumnsWithDefaultValue = append(blankColumnsWithDefaultValue, scope.Quote(field.DBName))
blankColumnsWithDefaultValue = append(blankColumnsWithDefaultValue, scope.Quote(field.DBName)) scope.InstanceSet("gorm:blank_columns_with_default_value", blankColumnsWithDefaultValue)
scope.InstanceSet("gorm:blank_columns_with_default_value", blankColumnsWithDefaultValue) } else if !field.IsPrimaryKey || !field.IsBlank {
} else { columns = append(columns, scope.Quote(field.DBName))
columns = append(columns, scope.Quote(field.DBName)) placeholders = append(placeholders, scope.AddToVars(field.Field.Interface()))
placeholders = append(placeholders, scope.AddToVars(field.Field.Interface()))
}
} }
} else if field.Relationship != nil && field.Relationship.Kind == "belongs_to" { } else if field.Relationship != nil && field.Relationship.Kind == "belongs_to" {
for _, foreignKey := range field.Relationship.ForeignDBNames { for _, foreignKey := range field.Relationship.ForeignDBNames {
@ -129,7 +127,13 @@ func createCallback(scope *Scope) {
// forceReloadAfterCreateCallback will reload columns that having default value, and set it back to current object // forceReloadAfterCreateCallback will reload columns that having default value, and set it back to current object
func forceReloadAfterCreateCallback(scope *Scope) { func forceReloadAfterCreateCallback(scope *Scope) {
if blankColumnsWithDefaultValue, ok := scope.InstanceGet("gorm:blank_columns_with_default_value"); ok { if blankColumnsWithDefaultValue, ok := scope.InstanceGet("gorm:blank_columns_with_default_value"); ok {
scope.DB().New().Select(blankColumnsWithDefaultValue.([]string)).First(scope.Value) db := scope.DB().New().Table(scope.TableName()).Select(blankColumnsWithDefaultValue.([]string))
for _, field := range scope.Fields() {
if field.IsPrimaryKey && !field.IsBlank {
db = db.Where(fmt.Sprintf("%v = ?", field.DBName), field.Field.Interface())
}
}
db.Scan(scope.Value)
} }
} }