最近使用gorm结构体来接收前端传的相关参数,并进行数据的增删改查操作。以前用原生语句接收完各类参数后,通过语句直接就拼成想要得语句,尤其是对于数据表字段相同的表,就只需要改下表名即可。但是用结构后,如何修改了呢,刚用这个gorm还是不太熟,记录一下我最终实现的方式吧。直接看最终代码
方法一:改表
结构体这样写
type ObjTable1 struct {
PrcoId int64 `gorm:"column:PROCID;type:bigint;comment:处置信息//处置Id,与报警Id对应,Key"`
RtuCode int64 `gorm:"column:RTUCODE;type:bigint;comment:终端号"`
AlarmCode int64 `gorm:"column:ALARMCODE;type:bigint;comment:报警代码:<-dic_alarm_type.Code)"`
AlarmId int64 `gorm:"column:ALARMID;type:bigint;comment:报警Id"`
AlarmId1 int64 `gorm:"column:ALARMID1;type:bigint;comment:相同报警原因的第1次报警Id"`
DispNO int64 `gorm:"column:DISPNO;type:bigint;comment:调度次数,相同报警原因可能有多次调度"`
AbnoGrade int64 `gorm:"column:ABNOGRADE;type:bigint;comment:异常级别:1-3"`
DispClass int64 `gorm:"column:DISPCLASS;type:bigint;comment:调度类型:1-4"`
DispDT time.Time `gorm:"column:DISPDT;comment:调度时间"`
DispType int64 `gorm:"column:DISPTYPE;type:bigint;comment:调度类型:sys_dict_type(cx_disp_type):0-未处置,1-继续观察,2-指令措施,3-派发任务"`
DispDesc string `gorm:"column:DISPDESC;type:varchar(1024);comment:对于:1-继续观察来说,观察多少时间;2-指令措施来说,就是发送的的指令,或设置前后的参数说明,3-派发任务来说,就是维护Id。"`
AllowMins int64 `gorm:"column:ALLOWMINS;type:bigint;comment:当前处置允许时长,分"`
AllowTotalMins int64 `gorm:"column:ALLOWTOTALMINS;type:bigint;comment:当前报警允许总时长,分"`
RemainMins int64 `gorm:"column:REMAINMINS;type:bigint;comment:当前处置剩余时长,分"`
MaintId int64 `gorm:"column:MAINTID;type:bigint;comment:维护号,<-obj_maint_hist.MaintId"`
ProcState int64 `gorm:"column:PROCSTATE;type:bigint;comment:处置状态:sys_dict_type(cx_proc_state):0-未处置,1-系统处置,2-人工处置,3-超时处置"`
//
TblName string `gorm:"-"`
}
//重写表名
func (v ObjTable1) TableName() string {
//初始化默认指向的表名
if v.TblName == "" {
return "OBJ_PROC_HIST"
}
return v.TblName
}
调用方法
大概像这样:
var req po.ObjTable1
err := c.ShouldBindJSON(&req)
err = global.DB.Create(&req).Error //A表插入一条记录
if err != nil {
c.JSON(http.StatusOK, vo.NewResp(utils.CodeFail, "执行失败", nil))
return
}
req.TblName = "OBJ_PROC" //指向b表
wdb := global.DB.Table(req.TableName())
err = wdb.Create(&req).Error//B表插入一条记录
方法二:2个结构体互传
这种方式就不多写了,可以解决问题,大概像这样:
//结构体如下
type A struct {
PrcoId int64 `gorm:"column:PROCID;type:bigint;comment:处置信息//处置Id,与报警Id对应,Key"`
RtuCode int64 `gorm:"column:RTUCODE;type:bigint;comment:终端号"`
}
type B struct {
PrcoId int64 `gorm:"column:PROCID;type:bigint;comment:处置信息//处置Id,与报警Id对应,Key"`
RtuCode int64 `gorm:"column:RTUCODE;type:bigint;comment:终端号"`
}
// TypeTo 类型转换, 需要json的tag标签一致
func TypeTo(request, response any) (err error) {
dataByte, err := json.Marshal(request)
if err != nil {
return
}
return json.Unmarshal(dataByte, response)
}
//调用
TypeTo(&A, &B)