// gorm.Model 定义 type Model struct { ID uint`gorm:"primary_key"` CreatedAt time.Time UpdatedAt time.Time DeletedAt *time.Time }
你可以将它嵌入到你自己的模型中:
1 2 3 4 5
// 将 `ID`, `CreatedAt`, `UpdatedAt`, `DeletedAt`字段注入到`User`模型中 type User struct { gorm.Model Name string }
也可以通过标签 embedded 将其嵌入,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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 中的字段名添加前缀,例如:
1 2 3 4 5 6 7 8 9 10 11 12
type Blog struct { ID int Author Author `gorm:"embedded;embeddedPrefix:author_"` Upvotes int32 } // 等效于 type Blog struct { ID int64 AuthorName string AuthorEmail string Upvotes int32 }
当然你也可以完全自己定义模型:
1 2 3 4 5
// 不使用gorm.Model,自行定义模型 type User struct { ID int Name string }
模型定义示例
1 2 3 4 5 6 7 8 9 10 11 12
type User struct { gorm.Model 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"`// 设置会员号(member number)唯一并且不为空 Num int`gorm:"AUTO_INCREMENT"`// 设置 num 为自增类型 Address string`gorm:"index:addr"`// 给address字段创建名为addr的索引 IgnoreMe int`gorm:"-"`// 忽略本字段 }
type User struct { ID uint// column name is `id` Name string// column name is `name` Birthday time.Time // column name is `birthday` CreatedAt time.Time // column name is `created_at` }
可以使用结构体tag指定列名:
1 2 3 4 5
type Animal struct { AnimalId int64`gorm:"column:beast_id"`// set column name to `beast_id` Birthday time.Time `gorm:"column:day_of_the_beast"`// set column name to `day_of_the_beast` Age int64`gorm:"column:age_of_the_beast"`// set column name to `age_of_the_beast` }
// 使用指针 type User struct { ID int64 Name *string`gorm:"default:galeone"` Age int64 } user := User{Name: new(string), Age: 18} db.Create(&user) // 此时数据库中该条记录name字段的值就是''
使用Scanner/Valuer接口方式实现零值存入数据库
1 2 3 4 5 6 7 8
// 使用 Scanner/Valuer type User struct { ID int64 Name sql.NullString `gorm:"default:'galeone'"`// sql.NullString 实现了Scanner/Valuer接口 Age int64 } user := User{Name: sql.NullString{Valid: true}, Age: 18} db.Create(&user) // 此时数据库中该条记录name字段的值就是''
扩展创建选项
例如PostgreSQL数据库中可以使用下面的方式实现合并插入, 有则更新, 无则插入。
1 2 3
// 为Instert语句添加扩展SQL选项 db.Set("gorm:insert_option", "ON CONFLICT").Create(&product) // INSERT INTO products (name, code) VALUES ("name", "code") ON CONFLICT;
// 根据主键查询第一条记录 var user User result := db.First(&user) fmt.Println(result.RowsAffected) // 返回找到的记录数 fmt.Println(result.Error) // returns error or nil //// SELECT * FROM users ORDER BY id LIMIT 1;
// 随机获取一条记录 db.Take(&user) //// SELECT * FROM users LIMIT 1;
// 根据主键查询最后一条记录 db.Last(&user) //// SELECT * FROM users ORDER BY id DESC LIMIT 1;
// 查询所有的记录 db.Find(&users) //// SELECT * FROM users;
// 查询指定的某条记录(仅当主键为整型时可用) db.First(&user, 10) //// SELECT * FROM users WHERE id = 10;
db.First(&user, 10) // SELECT * FROM users WHERE id = 10;
db.First(&user, "10") // SELECT * FROM users WHERE id = 10;
db.Find(&users, []int{1,2,3}) // SELECT * FROM users WHERE id IN (1,2,3);
//主键为字符串 db.First(&user, "id = ?", "1b74413f-f3b8-409f-ac47-e8c062e3472a") // SELECT * FROM users WHERE id = "1b74413f-f3b8-409f-ac47-e8c062e3472a"
// Get first matched record db.Where("name = ?", "jinzhu").First(&user) //// SELECT * FROM users WHERE name = 'jinzhu' limit 1;
// Get all matched records db.Where("name = ?", "jinzhu").Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu';
// <> db.Where("name <> ?", "jinzhu").Find(&users) //// SELECT * FROM users WHERE name <> 'jinzhu';
// IN db.Where("name IN (?)", []string{"jinzhu", "jinzhu 2"}).Find(&users) //// SELECT * FROM users WHERE name in ('jinzhu','jinzhu 2');
// LIKE db.Where("name LIKE ?", "%jin%").Find(&users) //// SELECT * FROM users WHERE name LIKE '%jin%';
// AND db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users) //// SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22;
// Time db.Where("updated_at > ?", lastWeek).Find(&users) //// SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00';
// BETWEEN db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users) //// SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00';
Struct & Map查询
1 2 3 4 5 6 7 8 9 10 11
// 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;
// 主键的切片 db.Where([]int64{20, 21, 22}).Find(&users) //// SELECT * FROM users WHERE id IN (20, 21, 22);
db.Where(&User{Name: "jinzhu", Age: 0}).Find(&users) //// SELECT * FROM users WHERE name = "jinzhu";
若要在查询条件中包含零值,可以使用映射,该映射将包含所有键值作为查询条件,例如:
1 2
db.Where(map[string]interface{}{"Name": "jinzhu", "Age": 0}).Find(&users) // SELECT * FROM users WHERE name = "jinzhu" AND age = 0;
指定结构体查询字段
在使用 struct 进行搜索时,可以通过传递相关的字段名或 dbname 到 Where ()来指定在查询条件中使用 struct 中的哪些特定值,例如:
1 2
db.Where(&User{Name: "jinzhu"}, "name", "Age").Find(&users)// SELECT * FROM users WHERE name = "jinzhu" AND age = 0; db.Where(&User{Name: "jinzhu"}, "Age").Find(&users)// SELECT * FROM users WHERE age = 0;
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";
Or条件
1 2 3 4 5 6 7 8 9 10
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", Age: 18}).Find(&users) // SELECT * FROM users WHERE name = 'jinzhu' OR (name = 'jinzhu 2' AND age = 18);
// Map db.Where("name = 'jinzhu'").Or(map[string]interface{}{"name": "jinzhu 2", "age": 18}).Find(&users) // SELECT * FROM users WHERE name = 'jinzhu' OR (name = 'jinzhu 2' AND age = 18);
// 未找到 user,则根据给定的条件以及 Attrs 初始化 user db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'non_existing' ORDER BY id LIMIT 1; // user -> User{Name: "non_existing", Age: 20}
// 未找到 user,则根据给定的条件以及 Attrs 初始化 user db.Where(User{Name: "non_existing"}).Attrs("age", 20).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'non_existing' ORDER BY id LIMIT 1; // user -> User{Name: "non_existing", Age: 20}
// 找到了 `name` = `jinzhu` 的 user,则忽略 Attrs db.Where(User{Name: "Jinzhu"}).Attrs(User{Age: 20}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = jinzhu' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "Jinzhu", Age: 18}
// 找到 `name` = `jinzhu` 的记录,依然会更新 Assign 相关的属性 db.Where(User{Name: "Jinzhu"}).Assign(User{Age: 20}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = jinzhu' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "Jinzhu", Age: 20}
// 未找到 user,根据条件和 Assign 属性创建记录 db.Where(User{Name: "non_existing"}).Attrs(User{Age: 20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'non_existing' ORDER BY id LIMIT 1; // INSERT INTO "users" (name, age) VALUES ("non_existing", 20); // user -> User{ID: 112, Name: "non_existing", Age: 20}
// 找到了 `name` = `jinzhu` 的 user,则忽略 Attrs db.Where(User{Name: "jinzhu"}).Attrs(User{Age: 20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1; // user -> User{ID: 111, Name: "jinzhu", Age: 18}
不管是否找到记录,Assign 都会将属性赋值给 struct,并将结果写回数据库
1 2 3 4 5 6 7 8 9 10 11
// 未找到 user,根据条件和 Assign 属性创建记录 db.Where(User{Name: "non_existing"}).Assign(User{Age: 20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'non_existing' ORDER BY id LIMIT 1; // INSERT INTO "users" (name, age) VALUES ("non_existing", 20); // user -> User{ID: 112, Name: "non_existing", Age: 20}
// 找到了 `name` = `jinzhu` 的 user,依然会根据 Assign 更新记录 db.Where(User{Name: "jinzhu"}).Assign(User{Age: 20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1; // UPDATE users SET age=20 WHERE id = 111; // user -> User{ID: 111, Name: "jinzhu", Age: 20}
高级查询
子查询
基于 *gorm.expr 的子查询
1 2 3 4 5 6
db.Where("amount > (?)", db.Table("orders").Select("AVG(amount)")).Find(&orders) // SELECT * FROM "orders" WHERE amount > (SELECT AVG(amount) FROM "orders");
subQuery := db.Select("AVG(age)").Where("name LIKE ?", "name%").Table("users") db.Select("AVG(age) as avgage").Group("name").Having("AVG(age) > (?)", subQuery).Find(&results) // SELECT AVG(age) as avgage FROM `users` GROUP BY `name` HAVING AVG(age) > (SELECT AVG(age) FROM `users` WHERE name LIKE "name%")
From 子查询
GORM 允许您在 Table 方法中通过 FROM 子句使用子查询,例如:
1 2 3 4 5 6 7
db.Table("(?) as u", db.Model(&User{}).Select("name", "age")).Where("age = ?", 18).Find(&User{}) // SELECT * FROM (SELECT `name`,`age` FROM `users`) as u WHERE `age` = 18
subQuery1 := db.Model(&User{}).Select("name") subQuery2 := db.Model(&Pet{}).Select("name") db.Table("(?) as u, (?) as p", subQuery1, subQuery2).Find(&User{}) // SELECT * FROM (SELECT `name` FROM `users`) as u, (SELECT `name` FROM `pets`) as p
选择字段
Select,指定你想从数据库中检索出的字段,默认会选择全部字段。
1 2 3 4 5 6 7 8
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;
db.Order("age desc, name").Find(&users) //// SELECT * FROM users ORDER BY age desc, name;
// 多字段排序 db.Order("age desc").Order("name").Find(&users) //// SELECT * FROM users ORDER BY age desc, name;
// 覆盖排序 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)
数量和偏移
Limit,指定从数据库检索出的最大记录数。Offset,指定开始返回记录前要跳过的记录数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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;
db.Limit(10).Offset(5).Find(&users) // SELECT * FROM users OFFSET 5 LIMIT 10;
// 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,该 model 能获取的记录总数。
1 2 3 4 5 6 7 8 9 10 11 12
db.Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Find(&users).Count(&count) //// SELECT * from USERS WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (users) //// SELECT count(*) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'; (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;
db.Table("deleted_users").Select("count(distinct(name))").Count(&count) //// SELECT count( distinct(name) ) FROM deleted_users; (count)
rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Rows() for rows.Next() { ... }
// 使用Scan将多条结果扫描进事先准备好的结构体切片中 type Result struct { Date time.Time Total int } var rets []Result db.Table("users").Select("date(created_at) as date, sum(age) as total").Group("date(created_at)").Scan(&rets)
rows, err := db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Rows() for rows.Next() { ... }
type Result struct { Date time.Time Total int64 } db.Table("orders").Select("date(created_at) as date, sum(amount) as total").Group("date(created_at)").Having("sum(amount) > ?", 100).Scan(&results)
Distinct
从模型中选择不同的值
1
db.Distinct("name", "age").Order("name, age desc").Find(&results)
var count int64 db.Model(&User{}).Where("name = ?", "jinzhu").Or("name = ?", "jinzhu 2").Count(&count) // SELECT count(1) FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2'
db.Model(&User{}).Where("name = ?", "jinzhu").Count(&count) // SELECT count(1) FROM users WHERE name = 'jinzhu'; (count)
db.Table("deleted_users").Count(&count) // SELECT count(1) FROM deleted_users;
// Count with Distinct db.Model(&User{}).Distinct("name").Count(&count) // SELECT COUNT(DISTINCT(`name`)) FROM `users`
db.Table("deleted_users").Select("count(distinct(name))").Count(&count) // SELECT count(distinct(name)) FROM deleted_users
// Count with Group users := []User{ {Name: "name1"}, {Name: "name2"}, {Name: "name3"}, {Name: "name3"}, }
// UPDATE users SET name='jinzhu 2', age=100, birthday='2016-01-01', updated_at = '2013-11-17 21:34:10' WHERE id=111;
更新单个列
1 2 3 4 5 6 7 8 9 10 11
// Update with conditions db.Model(&User{}).Where("active = ?", true).Update("name", "hello") // UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE active=true;
// User's ID is `111`: db.Model(&user).Update("name", "hello") // UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111;
// Update with conditions and model value db.Model(&user).Where("active = ?", true).Update("name", "hello") // UPDATE users SET name='hello', updated_at='2013-11-17 21:34:10' WHERE id=111 AND active=true;
更新多列
1 2 3 4 5 6 7
// Update attributes with `struct`, will only update non-zero fields db.Model(&user).Updates(User{Name: "hello", Age: 18, Active: false}) // UPDATE users SET name='hello', age=18, updated_at = '2013-11-17 21:34:10' WHERE id = 111;
// Update attributes with `map` db.Model(&user).Updates(map[string]interface{}{"name": "hello", "age": 18, "active": false}) // UPDATE users SET name='hello', age=18, active=false, updated_at='2013-11-17 21:34:10' WHERE id=111;
// 更新单个属性,类似于 `Update` db.Model(&user).UpdateColumn("name", "hello") //// UPDATE users SET name='hello' WHERE id = 111;
// 更新多个属性,类似于 `Updates` db.Model(&user).UpdateColumns(User{Name: "hello", Age: 18}) //// UPDATE users SET name='hello', age=18 WHERE id = 111;
批量更新
如果我们没有使用 Model 指定主键值的记录,GORM 将执行批量更新,批量更新时Hooks(钩子函数)不会运行。
1 2 3 4 5 6 7 8 9 10
// Update with struct db.Model(User{}).Where("role = ?", "admin").Updates(User{Name: "hello", Age: 18}) // UPDATE users SET name='hello', age=18 WHERE role = 'admin';
// Update with map db.Table("users").Where("id IN ?", []int{10, 11}).Updates(map[string]interface{}{"name": "hello", "age": 18}) // UPDATE users SET name='hello', age=18 WHERE id IN (10, 11);