You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
3.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package gormExample
import (
"fmt"
"gorm.io/gorm"
"log"
)
func UpdatePK() {
var c Content
// 无主键
if err := DB.Save(&c).Error; err != nil {
log.Fatalln(err)
}
// [12.300ms] [rows:1] INSERT INTO `msb_content` (`created_at`,`updated_at`,`deleted_at`,`subject`,`likes`,`views`,`publish_time`,`author_id`) VALUES ('2023-04-21 16:42:35.089','2023-04-21 16:42:35.089',NULL,'',0,0,'2023-04-21 16:42:35.089',0) ON DUPLICATE KEY UPDATE `updated_at`='2023-04-21 16:42:35.089',`deleted_at`=VALUES(`deleted_at`),`subject`=VALUES(`subject`),`likes`=VALUES(`likes`),`views`=VALUES(`views`),`publish_time`=VALUES(`publish_time`),`author_id`=VALUES(`author_id`)
fmt.Printf("%+v\n", c)
// 具有主键ID
if err := DB.Save(&c).Error; err != nil {
log.Fatalln(err)
}
// [9.316ms] [rows:1] UPDATE `msb_content` SET `created_at`='2023-04-21 16:45:22.294',`updated_at`='2023-04-21 16:45:22.306',`deleted_at`=NULL,`subject`='',`likes`=0,`views`=0,`publish_time`='2023-04-21 16:45:22.293',`author_id`=0 WHERE `msb_content`.`deleted_at` IS NULL AND `id` = 61
fmt.Printf("%+v\n", c)
}
func UpdateWhere() {
// 更新的字段值数据
// map推荐
values := map[string]any{
"subject": "Where Update Row",
"likes": 10001,
}
// 执行带有条件的更新
result := DB.Model(&Content{}).
//Omit("updated_at").
Where("likes > ?", 100).
Updates(values)
if result.Error != nil {
log.Fatalln(result.Error)
}
// 获取更新结果,更新的记录数量(受影响的记录数)
// 指的是修改的记录数,而不是满足条件的记录数
log.Println("updated rows num: ", result.RowsAffected)
}
func UpdateNoWhere() {
// 更新的字段值数据
// map推荐
values := map[string]any{
"subject": "Where Update Row",
"likes": 1001,
}
// 执行带有条件的更新
result := DB.Model(&Content{}).
// 全局更新
Where("1=1").
Updates(values)
if result.Error != nil {
log.Fatalln(result.Error)
}
// 获取更新结果,更新的记录数量(受影响的记录数)
// 指的是修改的记录数,而不是满足条件的记录数
log.Println("updated rows num: ", result.RowsAffected)
}
func UpdateExpr() {
// 更新的字段值数据
// map推荐
values := map[string]any{
"subject": "Where Update Row",
// 值为表达式计算的结果时使用Expr类型
"likes": gorm.Expr("likes + ?", 10),
//"likes": "likes + 10",
// Incorrect integer value: 'likes + 10' for column 'likes' at row 1
}
// 执行带有条件的更新
result := DB.Model(&Content{}).
Where("likes > ?", 100).
Updates(values)
// [17.011ms] [rows:51] UPDATE `msb_content` SET `likes`=likes + 10,`subject`='Where Update Row',`updated_at`='2023-04-21 17:28:45.498' WHERE likes > 100 AND `msb_content`.`deleted_at` IS NULL
if result.Error != nil {
log.Fatalln(result.Error)
}
// 获取更新结果,更新的记录数量(受影响的记录数)
// 指的是修改的记录数,而不是满足条件的记录数
log.Println("updated rows num: ", result.RowsAffected)
}