1.安装
go get -u github.com/jinzhu/gorm
2.连接数据库(以Mysql为例)
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main() {
db, err := gorm.Open("mysql", "user:password@/dbname?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
}
3.结构体实例,注意:首字母要大写
type User struct {
gorm.Model
Name string
}
4.检查表users是否存在
db.HasTable("users")
db.HasTable(&User{})
5.创建表
db.CreateTable(&User{})//如果表已存在,会抛异常
// 指定表名
db.Table("deleted_users").CreateTable(&User{})
6.删除表
db.DropTable("users")
db.DropTable(&User{})
7.修改列的数据类型
db.Model(&User{}).ModifyColumn("name", "text")
8.删除列
db.Model(&User{}).DropColumn("name")
9.添加索引
db.Model(&User{}).AddIndex("idx_user_name", "name")
10.添加组合索引
db.Model(&User{}).AddIndex("idx_user_name_age", "name", "city_id")
11.添加唯一索引
db.Model(&User{}).AddUniqueIndex("idx_user_name", "name")
12.删除索引
db.Model(&User{}).RemoveIndex("idx_user_name_age")
13.模型的定义
type Email struct {
ID int
UserID int `gorm:"index"` // 外键 (属于), tag `index`是为该列创建索引
Email string `gorm:"type:varchar(100);unique_index"` // `type`设置sql类型, `unique_index` 为该列设置唯一索引
Subscribed bool
}
type Address struct {
ID int
Address1 string `gorm:"not null;unique"` // 设置字段为非空并唯一
Address2 string `gorm:"type:varchar(100);unique"`
Post sql.NullString `gorm:"not null"`
}
type Language struct {
ID int
Name string `gorm:"index:idx_name_code"` // 创建索引并命名,如果找到其他相同名称的索引则创建组合索引
Code string `gorm:"index:idx_name_code"` // `unique_index` also works
}
type User struct {
gorm.Model
Birthday time.Time
Age int
Name string `gorm:"size:255"` // string默认长度为255, 使用这种tag重设。
Num int `gorm:"AUTO_INCREMENT"` // 自增
CreditCard CreditCard // One-To-One (拥有一个 - CreditCard表的UserID作外键)
Emails []Email // One-To-Many (拥有多个 - Email表的UserID作外键)
BillingAddress Address // One-To-One (属于 - 本表的BillingAddressID作外键)
BillingAddressID sql.NullInt64
ShippingAddress Address // One-To-One (属于 - 本表的ShippingAddressID作外键)
ShippingAddressID int
IgnoreMe int `gorm:"-"` // 忽略这个字段
Languages []Language `gorm:"many2many:user_languages;"` // Many-To-Many , 'user_languages'是连接表
}
14.全局禁用表名复数
db.SingularTable(true)
15.重设列名
type Animal struct {
AnimalId int64 `gorm:"column:beast_id"` // 设置列名为`beast_id`
Birthday time.Time `gorm:"column:day_of_the_beast"` // 设置列名为`day_of_the_beast`
Age int64 `gorm:"column:age_of_the_beast"` // 设置列名为`age_of_the_beast`
}
16.字段ID为主键
type User struct {
ID uint // 字段`ID`为默认主键
Name string
}
// 使用tag`primary_key`用来设置主键
type Animal struct {
AnimalId int64 `gorm:"primary_key"` // 设置AnimalId为主键
Name string
Age int64
}
17.插入一条记录
user := User{Name: "Jinzhu", Age: 18, Birthday: time.Now()}
db.NewRecord(user) // => 主键为空返回`true`
db.Create(&user)
ps:如果插入时不指定主键ID的值,默认是+1递增;如果插入指定主键的值出现了重复,插入不成功,但是也不会报错误
18.在表字段中设置默认值
type Animal struct {
ID int64
Name string `gorm:"default:'galeone'"`
Age int64
}