GORM模型删除
GORM模型删除
一、删除记录
package main
import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type UsersUpdate struct {
gorm.Model
//Name *string `gorm:"type:varchar(100);default:RandySun;comment:姓名"`
Name string `gorm:"type:varchar(100);default:RandySun;comment:姓名"`
Age int64
// 设置默认值
Active bool
}
func main() {
dsn := "root:@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic(err)
}
// 迁移表创建对应关系
db.AutoMigrate(&UsersUpdate{})
// 添加数据
db.Debug().Create(&UsersUpdate{Name: "bary", Age: 18})
db.Debug().Create(&UsersUpdate{Name: "RandySun", Age: 18})
db.Debug().Create(&UsersUpdate{Name: "Jack", Age: 18})
db.Debug().Create(&UsersUpdate{Name: "", Age: 19}) // 添加记录name默认为Null
//// 查询
var user UsersUpdate
db.Debug().First(&user)
fmt.Printf("%#v", user)
}
警告 删除记录时,请确保主键字段有值,GORM 会通过主键去删除记录,如果主键为空,GORM 会删除该 model 的所有记录。
var user UsersUpdate
db.Debug().First(&user)
fmt.Printf("%#v", user)
// 删除现有记录
// UPDATE `users_updates` SET `deleted_at`='2021-11-24 09:07:51.079' WHERE `users_updates`.`id` = 1 AND `users_updates`.`deleted_at` IS NULL
db.Debug().Delete(&user)
// 为删除 SQL 添加额外的 SQL 操作
// DELETE from emails where id=10 OPTION (OPTIMIZE FOR UNKNOWN);
db.Set("gorm:delete_option", "OPTION (OPTIMIZE FOR UNKNOWN)").Delete(&email)
二、批量删除
删除全部匹配的记录
var user UsersUpdate
db.Debug().First(&user)
fmt.Printf("%#v", user)
// UPDATE `users_updates` SET `deleted_at`='2021-11-24 22:10:16.311' WHERE name LIKE '%he%' AND `users_updates`.`id` = 1 AND `users_updates`.
`deleted_at` IS NULL
db.Debug().Where("name LIKE ?", "%he%").Delete(&user)
// DELETE from `users_updates` where name LIKE "%Randy%";
db.Debug().Delete(UsersUpdate{}, "name LIKE ?", "%Randy%")
三、软删除
如果一个 model 有 DeletedAt
字段,他将自动获得软删除的功能! 当调用 Delete
方法时, 记录不会真正的从数据库中被删除, 只会将DeletedAt
字段的值会被设置为当前时间
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
db.Delete(&user)
// 批量删除
// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE age = 20;
db.Where("age = ?", 20).Delete(&User{})
// 查询记录时会忽略被软删除的记录
// SELECT * FROM users WHERE age = 20 AND deleted_at IS NULL;
db.Where("age = 20").Find(&user)
// Unscoped 方法可以查询被软删除的记录
// SELECT * FROM users WHERE age = 20;
db.Unscoped().Where("age = 20").Find(&users)
四、物理删除
// Unscoped 方法可以物理删除记录
//// DELETE FROM orders WHERE id=10;
db.Unscoped().Delete(&order)
在当下的阶段,必将由程序员来主导,甚至比以往更甚。