Gorm 简单应用

本文将介绍Gorm,一个流行的Golang ORM库,用于简化数据库操作。通过实例演示如何使用Gorm进行数据模型定义、基本CRUD操作以及事务处理,帮助Go开发者快速理解并应用Gorm。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Gorm 简单应用

package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/plugin/soft_delete"
	"log"
	"os"
	"time"
)

// odf和odfhistory共有的字段结构,单独列出来,然后不同的再在其自己的结构体中设计
type OdfModels struct {
   
	ID     int    `json:"id" gorm:"column:id;primaryKey;autoIncrement;<-:false;comment:主键ID;not null"`
	OdfSn string	`json:"sn" gorm:"column:sn;index:idx_sn_deleted_time,unique,priority:1;comment:sn;not null"`
	CreatedTime time.Time  `json:"created_time" gorm:"column:created_time;autoCreateTime;type:datetime;<-:create;comment:创建时间;not null"`
	LastUpdateTime time.Time `json:"last_update_time" gorm:"column:last_update_time;autoUpdateTime;type:datetime;comment:更新时间;not null"`
}

// ODF odf表 在这里DeletedTime使用的是gorm插件的变量类型,这样在Delete的时候会使用软删除的方式,这个变量在数据库的类型是int时间戳,并且在这里设计了sn和deleted_time的联合唯一,以及
type ODF struct {
   
	OdfModels
	Odfhistory  []ODFHistory  `gorm:"foreignKey:record_id"`
	DeletedTime  soft_delete.DeletedAt  `json:"deleted_time" gorm:"column:deleted_time;default:0;type:int(11);index:idx_sn_deleted_time,unique,priority:2;comment:删除时间"`
}
func (t *ODF) TableName() string {
   
	return "odf"
}

// ODFHistory odf历史记录 在这里DeletedTime使用的是gorm内置的变量类型,这样在Delete的时候会使用软删除的方式,这个变量在数据库的类型是datetime,这里deleted_time后面的tag 建立的联合索引不能删除,删除的话会建立一个sn的唯一索引,不符合历史记录这个设定了
type ODFHistory struct {
   
	OdfModels
	Action string `json:"action" gorm:"column:action;<-:create;comment:动作;not null"`
	RecordID int `json:"record_id" gorm:"column:record_id;<-:create;comment:关联ID;not null"`
	DeletedTime  gorm.DeletedAt   `json:"deleted_time" gorm:"column:deleted_time;index:idx_sn_deleted_time,unique,priority:2;comment:删除时间"`
}
func (t *ODFHistory) TableName
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值