[GO] gorm批量操作

时间:2025-02-23 08:34:33

批量查询

gorm有封装批量创建的方法FindInBatches,但毕竟复杂,之后再研究研究。
使用IN关键字,根据切片来进行批量查询

// 根据goodIds批量查询商品
// 设Goods为已有结构体
var goods []Goods
app.Db.Debug().Model(&Goods{}).Where("good_id in (?)", goodIds).Find(&goods)

批量创建

gorm有封装批量创建的方法CreateInBatches

// 定义
func (db *DB) CreateInBatches(value interface{}, batchSize int) (tx *DB){}

// 具体用法
app.Db.Model(&pkg.GoodsSku{}).CreateInBatches(goodsSkuList, len(goodsSkuList))

批量更新

IN关键字
批量更新的话,只能批量对行的某些字段改为相同的值,不能改为不同的值…感觉没啥用

db.Table("users").Where("id IN (?)", []int{10, 11}).Updates(map[string]interface{}{"name": "hello", "age": 18})

 UPDATE users SET name='hello', age=18 WHERE id IN (10, 11);

批量删除

db.Where("email LIKE ?", "%jinzhu%").Delete(Email{})
// DELETE from emails where email LIKE "%jinzhu%";

db.Delete(Email{}, "email LIKE ?", "%jinzhu%")
// DELETE from emails where email LIKE "%jinzhu%";