i need add up values based on column its value if key has exist already.
the code below works as well. but it looks dumb if there's a lot of columns to upsert.
is there a elegant way to do same thing with gorm?
thanks for any help. ^_^
CREATE TABLE `daily_report` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`day` INT UNSIGNED NOT NULL,
`orders` INT UNSIGNED NOT NULL DEFAULT 0,
`money` DECIMAL(17,4) NOT NULL DEFAULT 0,
`effective_amount` DECIMAL(17,4) NOT NULL DEFAULT 0,
PRIMARY KEY (`id`) USING BTREE,
UNIQUE `idx_day` (`day`) USING BTREE
) ENGINE=INNODB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4;
type DailyReport struct {
Day int64
Orders int
Money float64
EffectiveAmount float64
}
func (d *DailyReport) Create(r []*DailyReport, db *gorm.DB) error {
return db.Clauses(
clause.OnConflict{
DoUpdates: clause.Assignments(map[string]interface{}{
"orders": gorm.Expr("`orders` + VALUES(`orders`)"),
"money": gorm.Expr("`money` + VALUES(`money`)"),
"effective_amount": gorm.Expr("`effective_amount` + VALUES(`effective_amount`)"),
}),
}).Create(&r).Error
}
var rows []*DailyReport
rows = append(rows, &DailyReport{
Day: 1001,
Orders: 10,
Money: 2000,
EffectiveAmount: 1000,
})
var r *DailyReport
_ = r.Create(rows, db)