go学习 --- gorm模型定义

go学习 --- gorm模型定义,第1张

一、gorm模型定义

 二、创建模型并生成表
package main

import (
	"database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_"github.com/jinzhu/gorm/dialects/mysql"
	"time"
)
//定义模型
type Users struct {
	gorm.Model //调用gorm框架定义好的模型
	Name string
	Age sql.NullInt64  //零值类型
	Birthday *time.Time
	Email string `gorm:"type:varchar(100);unique_index"`
	Role string `gorm:"size:255"` //设置字段大小255
	MemberNumber *string `gorm:"unique;not null"`//唯一,不为空
	Num int `gorm:"AUTO_INCREMENT"` //设置num为自增类型
	Address string `gorm:"index:addr"` //给address字段创建名为addr的索引
	IgnoreMe int `grom:"-"`//忽略本字段

}
func main() {
	//连接数据库
	db, err := gorm.Open("mysql", "root:123456@(localhost:3306)/db01?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println("连接数据库错误",err)
		panic(err)
	}
	//关闭连接
	defer db.Close()
	//创建表
	db.AutoMigrate(&Users{})
}

三、1、 自定义表名
package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)
//定义模型
type Animal struct {
	AnimalID int64 `gorm:"primary_key"`
	Name string
	Age int64
}
//不使用默认生成的表名
func (Animal) TableName() string {
	return "Animal"
}
func main() {
	//连接数据库
	db, err := gorm.Open("mysql", "root:123456@(localhost:3306)/db01?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println("连接数据库错误",err)
		panic(err)
	}
	//关闭连接
	defer db.Close()
	//创建表
	db.AutoMigrate(&Animal{})
}
2、采用禁用复数
package main

import (
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)
//定义模型
type Animal struct {
	AnimalID int64 `gorm:"primary_key"`
	Name string
	Age int64
}

func main() {
	//连接数据库
	db, err := gorm.Open("mysql", "root:123456@(localhost:3306)/db01?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		fmt.Println("连接数据库错误",err)
		panic(err)
	}
	//关闭连接
	defer db.Close()
	db.SingularTable(true)//禁用复数
	//创建表
	db.AutoMigrate(&Animal{})
}

 

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/995773.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-21
下一篇2022-05-21

发表评论

登录后才能评论

评论列表(0条)

    保存