github.com/jinzhu/gorm
注意:
实体类结构体中,要映射到数据库的字段首字母必须大写,否则会被忽略
可以通过定义嵌套gorm.Model这个结构体的类型来定义实体类,gorm.Model中定义了数据库表的一些常用基本字段
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
比如我们定义User实体
type User struct{
gorm.Model
Name string
}
开启连接参数字符串格式如下
username:password@protocol(address)/dbname?param=value
其中如果protocol和address是默认值,可以直接省略,比如
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func main(){
db, err := gorm.Open("mysql", "root:root@/gorm?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
}
创建表默认使用结构体类型名称的驼峰命名复数形式作为表名,比如User就是users 通过
db.SingularTable(true)
设定不使用复数形式,则User对应的表为user CreateTable方法接收一个interface{}类型,创建对应结构体类型的表。如果创建的表已经存在,会抛出异常 比如
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
gorm.Model
Name string
}
func main() {
db, _ := gorm.Open("mysql", "root:root@/gorm?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
db.CreateTable(&User{}) //创建表名users
}
AutoMigrate方法与CreateTable用法类似,不同的是,如果表已经存在,AutoMigrate也不会抛出异常,而是使用当前传入的最新结构体更新表结构,如果表不存在,则与CreateTable表现一样,所以刚刚的
db.CreateTable(&User{})
也可以使用下面语句替代
db.AutoMigrate(&User{})
gorm.Model的主键ID为整数类型,映射到数据库时为自动递增主键 Save方法接收一个结构体指针对象
db, _ := gorm.Open("mysql", "root:root@/gorm?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
db.AutoMigrate(&User{})
user := User{Name: "aa"}
db.Save(&user)
//新增成功后,如果主键是由数据库生成,会将主键回显到实体对象的属性
println(user.ID)
user.Name = "bb"
db.Save(&user)//更新
Create方法用法与Save类似,不同的是Create方法只能用于插入,如果对象具备主键,并且数据库中已经存在该主键记录,则抛出异常
db, _ := gorm.Open("mysql", "root:root@/gorm?charset=utf8&parseTime=True&loc=Local")
defer db.Close()
db.AutoMigrate(&User{})
user := User{Name: "aa"}
db.Create(&user) //没有设定主键,默认由数据库自增
println(user.ID)
NewRecord方法用于判断某个对象是否可以作为新纪录插入,如果该对象主键为空或者0,或者数据库表中不存在该主键记录,返回true,否则返回false,所以可以用于辅助Create方法
...
if(db.NewRecord(&user)){
db.Create(&user)
}
Update和Updates方法提供对记录进行更新操作,可以通过Map或者struct传递更新属性,建议通过Map 因为通过struct更新时,FORM将仅更新具有非空值的字段
// 使用`map`更新多个属性,只会更新这些更改的字段
db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "actived": false})
// 使用组合条件批量更新单个属性
db.Model(&user).Where("name= ?", "aa").Update("name", "hello")
//// UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND name='aa';
// 使用`struct`更新多个属性,只会更新这些更改的和非空白字段
db.Model(&user).Updates(User{Name: "hello", Age: 18})
//// UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;
// 对于下面的更新,什么都不会更新为"",0,false是其类型的空白值
db.Model(&user).Updates(User{Name: "", Age: 0, Actived: false})
通过Delete方法删除记录,如果记录中包含了DeletedAt字段,那么将不会真正删除该记录,只是设置了该记录的该字段为当前时间(软删除),通过Unscoped方法的返回对象调用Find、Delete可以执行到被软删除的对象,进行查询或者永久删除
db.Delete(&user)
//// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE id = 111;
// 批量删除
db.Where("name = ?", "aa").Delete(&User{})
//// UPDATE users SET deleted_at="2013-10-29 10:23" WHERE name = 'aa';
// 软删除的记录将在查询时被忽略
db.Where("name = 'aa'").Find(&user)
//// SELECT * FROM users WHERE name = 'aa' AND deleted_at IS NULL;
// 使用Unscoped查找软删除的记录
db.Unscoped().Where("name = 'aa'").Find(&users)
//// SELECT * FROM users WHERE name = 'aa';
// 使用Unscoped永久删除记录
db.Unscoped().Delete(&order)
//// DELETE FROM orders WHERE id=10;
查询一般通过传入接收结果的结构体对象或者slice,来接受结果,需要注意的是,如果传入Find、First、Last等方法的结构体对象设置了主键值,则该主键值会作为查询条件之一 通过Where方法创建查询条件对象(可选,不使用为全表数据),然后使用
// 获取第一条记录,按主键排序
db.First(&user)
//// SELECT * FROM users ORDER BY id LIMIT 1;
// 获取最后一条记录,按主键排序
db.Last(&user)
//// SELECT * FROM users ORDER BY id DESC LIMIT 1;
// 获取所有记录
db.Find(&users)
//// SELECT * FROM users;
// 按主键获取
db.First(&user, 23)
//// SELECT * FROM users WHERE id = 23 LIMIT 1;
// 简单SQL
db.Find(&user, "name = ?", "jinzhu")
//// SELECT * FROM users WHERE name = "jinzhu";
db.Find(&users, "name <> ? AND age > ?", "jinzhu", 20)
//// SELECT * FROM users WHERE name <> "jinzhu" AND age > 20;
// Struct
db.Find(&users, User{Age: 20})
//// SELECT * FROM users WHERE age = 20;
// Map
db.Find(&users, map[string]interface{}{"age": 20})
//// SELECT * FROM users WHERE age = 20;
db.Modal(&User{}).Find(&users)
// 获取第一个匹配记录
db.Where("name = ?", "jinzhu").First(&user)
//// SELECT * FROM users WHERE name = 'jinzhu' limit 1;
// 获取所有匹配记录
db.Where("name = ?", "jinzhu").Find(&users)
//// SELECT * FROM users WHERE name = 'jinzhu';
db.Where("name <> ?", "jinzhu").Find(&users)
// IN
db.Where("name in (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users)
// LIKE
db.Where("name LIKE ?", "%jin%").Find(&users)
// AND
db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
// Time
db.Where("updated_at > ?", lastWeek).Find(&users)
db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
// Struct
db.Where(&User{Name: "jinzhu", Age: 20}).First(&user)
//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20 LIMIT 1;
// Map
db.Where(map[string]interface{}{"name": "jinzhu", "age": 20}).Find(&users)
//// SELECT * FROM users WHERE name = "jinzhu" AND age = 20;
// 主键的Slice
db.Where([]int64{20, 21, 22}).Find(&users)
//// SELECT * FROM users WHERE id IN (20, 21, 22);
db.Not("name", "jinzhu").First(&user)
//// SELECT * FROM users WHERE name <> "jinzhu" LIMIT 1;
// Not In
db.Not("name", []string{"jinzhu", "jinzhu 2"}).Find(&users)
//// SELECT * FROM users WHERE name NOT IN ("jinzhu", "jinzhu 2");
// Not In slice of primary keys
db.Not([]int64{1,2,3}).First(&user)
//// SELECT * FROM users WHERE id NOT IN (1,2,3);
db.Not([]int64{}).First(&user)
//// SELECT * FROM users;
// Plain SQL
db.Not("name = ?", "jinzhu").First(&user)
//// SELECT * FROM users WHERE NOT(name = "jinzhu");
// Struct
db.Not(User{Name: "jinzhu"}).First(&user)
//// SELECT * FROM users WHERE name <> "jinzhu";
db.Where("role = ?", "admin").Or("role = ?", "super_admin").Find(&users)
//// SELECT * FROM users WHERE role = 'admin' OR role = 'super_admin';
// Struct
db.Where("name = 'jinzhu'").Or(User{Name: "jinzhu 2"}).Find(&users)
//// SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';
// Map
db.Where("name = 'jinzhu'").Or(map[string]interface{}{"name": "jinzhu 2"}).Find(&users)
多个查询条件可以直接拼接构建复合条件
db.Where("name <> ?","jinzhu").Where("age >= ? and role <> ?",20,"admin").Find(&users)
//// SELECT * FROM users WHERE name <> 'jinzhu' AND age >= 20 AND role <> 'admin';
db.Where("role = ?", "admin").Or("role = ?", "super_admin").Not("name = ?", "jinzhu").Find(&users)
通过Select方法进行部分字段的查询
db.Select("name, age").Find(&users)
//// SELECT name, age FROM users;
db.Select([]string{"name", "age"}).Find(&users)
//// SELECT name, age FROM users;
db.Table("users").Select("COALESCE(age,?)", 42).Rows()
//// SELECT COALESCE(age,'42') FROM users;
通过Order方法对返回结果进行排序
db.Order("age desc, name").Find(&users)
//// SELECT * FROM users ORDER BY age desc, name;
// Multiple orders
db.Order("age desc").Order("name").Find(&users)
//// SELECT * FROM users ORDER BY age desc, name;
// ReOrder
db.Order("age desc").Find(&users1).Order("age", true).Find(&users2)
//// SELECT * FROM users ORDER BY age desc; (users1)
//// SELECT * FROM users ORDER BY age; (users2)
db.Limit(3).Find(&users)
//// SELECT * FROM users LIMIT 3;
// Cancel limit condition with -1
db.Limit(10).Find(&users1).Limit(-1).Find(&users2)
//// SELECT * FROM users LIMIT 10; (users1)
//// SELECT * FROM users; (users2)
db.Offset(3).Find(&users)
//// SELECT * FROM users OFFSET 3;
// Cancel offset condition with -1
db.Offset(10).Find(&users1).Offset(-1).Find(&users2)
//// SELECT * FROM users OFFSET 10; (users1)
//// SELECT * FROM users; (users2)
count方法返回结果条数
db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count)
//// SELECT count(*) FROM users WHERE name = 'jinzhu'; (count)
db.Table("deleted_users").Count(&count)
//// SELECT count(*) FROM deleted_users;
通过Join方法进行多表查询
db.Table("users")
.Select("users.name, emails.email")
.Joins("left join emails on emails.user_id = users.id")
因为多表查询结果与实体类不对应,所以数据回显要通过Scan方法回显到任意定义结构体
Scan方法将结果扫描到另一个结构中。比如
type User struct{}
type Email struct{}
type result struct{
User
Email
}
func main(){
...
user := User{}
db.Modal(&User{}).Where("1 = 1").Scan(&user)
...
res := make([]Result,1)
db.Table("users")
.Select("users.name, emails.email")
.Joins("left join emails on emails.user_id = users.id")
.Scan(&res)
}
通过Scopes可以将Where语句封装为方法来使用,动态添加参数
func OrderStatus(status []string) func (db *gorm.DB) *gorm.DB {
return func (db *gorm.DB) *gorm.DB {
return db.Scopes(AmountGreaterThan1000).Where("status in (?)", status)
}
}
db.Scopes(OrderStatus([]string{"paid", "shipped"})).Find(&orders)
// 查找所有付费,发货订单
//User属于Profile, ProfileID为外键
type User struct {
gorm.Model
Profile Profile
ProfileID int
}
type Profile struct {
gorm.Model
Name string
}
db.Model(&user).Related(&profile)
//// SELECT * FROM profiles WHERE id = 111; // 111是user的外键ProfileID
通过配置ForeignKey指定该关联属性对应在本结构体的外键
通过配置AssociationForeignKey指定该关联属性在其关联结构体的外键属性
type Profile struct {
gorm.Model
Refer string
Name string
}
type User struct {
gorm.Model
Profile Profile `gorm:"ForeignKey:ProfileID;AssociationForeignKey:Refer"`
ProfileID int
}
// User 包含多个 emails, UserID 为外键
type User struct {
gorm.Model
Emails []Email
}
type Email struct {
gorm.Model
Email string
UserID uint
}
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111; // 111 是 user 的主键
type CustomizePerson struct {
IdPerson string
`gorm:"primary_key:true"`
Accounts []CustomizeAccount `gorm:"many2many:PersonAccount;ForeignKey:IdPerson;AssociationForeignKey:IdAccount"`
}
type CustomizeAccount struct {
IdAccount string
`gorm:"primary_key:true"`
Name string
}
type Cat struct {
Id int
Name string
Toy Toy `gorm:"polymorphic:Owner;"`
}
type Dog struct {
Id int
Name string
Toy Toy `gorm:"polymorphic:Owner;"`
}
type Toy struct {
Id int
Name string
OwnerId int
OwnerType string
}
当保存的实体类包含关联对象时,则会save该关联对象,比如下面代码,从数据库查出user对象,在保存car时,因为car的关联对象owners有值,关联关系和对应的user对象都被修改,名称更新为yyt
type User struct {
gorm.Model
Name string
A int
Cars []Car `gorm:"many2many:car_user;ForeignKey:ID;AssociationForeignKey:ID"`
}
type Car struct {
gorm.Model
Num string
Owners []User `gorm:"many2many:car_user;ForeignKey:ID;AssociationForeignKey:ID"`
}
func main(){
...
test := User{}
db.Model(&User{}).Where("1 = 1").First(&test)
println(test.ID)
test.Name = "yyt"
db.Save(&Car{
Num: "sssfs",
Owners: []User{test},
})
}
如果不想开启该关联更新有两个方式,如下是实时设定当前操作不进行关联更新的
db.Set("gorm:save_associations", false).Create(&user)
另一种方式是在定义结构体的tag里设定save_associations:false来指定不进行关联更新
type User struct {
gorm.Model
Name string
CompanyID uint
Company Company `gorm:"save_associations:false"`
}
type Company struct {
gorm.Model
Name string
}
在关联查询中,db.Modal接收的参数不再只是为了确定表,其必须是一个设定了主键的对象,否则会报错 关联查询查询该主键关联的其他表的数据
// User 包含多个 emails, UserID 为外键
type User struct {
gorm.Model
Emails []Email
Car Car
}
type Email struct {
gorm.Model
Email string
UserID uint
}
type Car struct {
gorm.Model
UserID uint
}
user : = User{}
user.ID = 111
emails := make([]Email,1)
db.Model(&user).Related(&emails)
//// SELECT * FROM emails WHERE user_id = 111; // 111 是 user 的主键
car := Car{}
db.Model(&user).Related(&car)
//// SELECT * FROM cars WHERE user_id = 111; // 111 是 user 的主键
// 开始关联模式
var user User
user.ID = 1
db.Model(&user).Association("Languages")
// user是源,它需要是一个有效的记录(包含主键)
// Languages是关系中源的字段名。
// 如果这些条件不匹配,将返回一个错误,检查它:
// db.Model(&user).Association("Languages").Error
// Query - 查找所有相关关联
db.Model(&user).Association("Languages").Find(&languages)
// Append - 添加新的many2many, has_many关联, 会替换掉当前 has_one, belongs_to关联
db.Model(&user).Association("Languages").Append([]Language{languageZH, languageEN})
db.Model(&user).Association("Languages").Append(Language{Name: "DE"})
// Delete - 删除源和传递的参数之间的关系,不会删除这些参数
db.Model(&user).Association("Languages").Delete([]Language{languageZH, languageEN})
db.Model(&user).Association("Languages").Delete(languageZH, languageEN)
// Replace - 使用新的关联替换当前关联
db.Model(&user).Association("Languages").Replace([]Language{languageZH, languageEN})
db.Model(&user).Association("Languages").Replace(Language{Name: "DE"}, languageEN)
// Count - 返回当前关联的计数
db.Model(&user).Association("Languages").Count()
// Clear - 删除源和当前关联之间的关系,不会删除这些关联
db.Model(&user).Association("Languages").Clear()
更多资料,请搜索公众号歪歪梯Club