-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0f67a6b
commit b0e81a3
Showing
1 changed file
with
36 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package gorm | ||
|
||
import ( | ||
"strings" | ||
|
||
"github.com/jinzhu/gorm" | ||
) | ||
|
||
// @desc 批量保存 如果唯一索引重复则更新,唯一索引不重复或者不存在唯一索引则插入 | ||
// @auth liuguoqiang 2020-04-21 | ||
// @param | ||
// @return | ||
func BulkSave(db *gorm.DB, table string, fields []string, params []map[string]interface{}) error { | ||
sql := "INSERT INTO `" + table + "` (" + strings.Join(fields, ",") + ") VALUES " | ||
updateArr := make([]string, 0) | ||
args := make([]interface{}, 0) | ||
valueArr := make([]string, 0) | ||
varArr := make([]string, 0) | ||
for _, value := range fields { | ||
updateArr = append(updateArr, value+"=VALUES("+value+")") | ||
} | ||
for _, obj := range params { | ||
varArr = varArr[:0] | ||
varStr := "(" | ||
for _, value := range fields { | ||
varArr = append(varArr, "?") | ||
args = append(args, obj[value]) | ||
} | ||
varStr += strings.Join(varArr, ",") + ")" | ||
valueArr = append(valueArr, varStr) | ||
} | ||
sql += strings.Join(valueArr, ",") | ||
sql += " ON DUPLICATE KEY UPDATE " + strings.Join(updateArr, ",") | ||
err := db.Exec(sql, args...).Error | ||
return err | ||
} |