From 907ea93b432f8bb236f183209750b31cc7a74d76 Mon Sep 17 00:00:00 2001 From: Paolo Galeone Date: Mon, 8 Dec 2014 19:00:02 +0100 Subject: [PATCH] Fixes scan when primary key is not defined in gorm (but is defined db-size). Useful in join tables --- callback_create.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/callback_create.go b/callback_create.go index 8e76e855..ed2589dd 100644 --- a/callback_create.go +++ b/callback_create.go @@ -35,9 +35,7 @@ func Create(scope *Scope) { } returningKey := "*" - if scope.PrimaryKey() == "" { - returningKey = "*" - } else { + if scope.PrimaryKey() != "" { returningKey = scope.PrimaryKey() } @@ -68,12 +66,24 @@ func Create(scope *Scope) { } } } else { - if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil { - scope.db.RowsAffected = 1 + if scope.PrimaryKey() == "" { + if rows, err := scope.DB().Query(scope.Sql, scope.SqlVars...); err != nil { + //extract column name to get fields lenght + if names, columnsErr := rows.Columns(); columnsErr != nil { + ids := make([]interface{}, len(names)) + if scope.Err(rows.Scan(ids...)) == nil { + scope.db.RowsAffected = int64(len(names)) + } + } + } + } else { + if scope.Err(scope.DB().QueryRow(scope.Sql, scope.SqlVars...).Scan(&id)) == nil { + scope.db.RowsAffected = 1 + } } } - if !scope.HasError() && scope.PrimaryKeyZero() { + if scope.PrimaryKey() != "" && !scope.HasError() && scope.PrimaryKeyZero() { scope.SetColumn(scope.PrimaryKey(), id) } }