GORM 自定义结构体关联的数据库表名称和自定义结构体字段对应的数据表字段名

8776人浏览 2021-02-23

GORM 自定义结构体关联的数据库表名称。

如下结构体:

//UserModel 用户信息
type UserModel struct {
	gorm.Model
	Id 			uint			`json:"id" gorm:"primaryKey"`
	UserName	string			`json:"username" gorm:"index"`
	Password 	string 			`json:"password"`
	Mail 		*string 		`json:"mail"`
	Phone 		string 			`json:"phone"`
	LoginIp		string			`json:"login_ip"`
	LoginNum	int64			`json:"login_num"`
	Authorize	string		    `json:"authorize"`
	Desc		string		    `json:"desc"`
	Status		byte		    `json:"status"`
	IsDeleted	byte		    `json:"is_deleted"`
	CreateAt 	time.Time 	    `json:"create_at"`
	UpdatedAt 	time.Time 	    `json:"updated_at"`
}

默认情况下此结构体映射的表明是"user_model",可使用以下方法,实现TableName接口自定义表名。

// TableName  自定义表明
func (this *UserModel) TableName() string  {
	return "f_system_user"
}

自定义结构体字段对应的数据表字段名:

type UserModel struct {
	ID 			uint			`json:"id" gorm:"primaryKey"`
	UserName	string			`json:"username"  gorm:"index;column:username"`
}

其中gorm:"column:username"用来自定义字段名。

 

GORM连表查询示例:

一对多:https://github.com/jouyouyun/examples/tree/master/gorm/related

一对一:https://blog.csdn.net/daimading/article/details/85258007

 

model模型嵌套

对于正常的结构体字段,你也可以通过标签 embedded 将其嵌入,例如:

type Author struct {
    Name  string
    Email string
}

type Blog struct {
  ID      int
  Author  Author `gorm:"embedded"`
  Upvotes int32
}
// 等效于
type Blog struct {
  ID    int64
  Name  string
  Email string
  Upvotes  int32
}

并且,您可以使用标签 embeddedPrefix 来为 db 中的字段名添加前缀,例如:

type Blog struct {
  ID      int
  Author  Author `gorm:"embedded;embeddedPrefix:author_"`
  Upvotes int32
}
// 等效于
type Blog struct {
  ID          int64
    AuthorName  string
    AuthorEmail string
  Upvotes     int32
}

 

 

推荐文章

KChatRoom在线多人聊天室,项目是使用Websocket和Gin框架基于Golang开发的在线聊天室
2021-05-17
Gin框架下获取所有路由信息
2021-07-14
Golang 使用excelize 导出表格到浏览器下载或者保存到本地。
2021-10-20
搜索文章