查询
// main.go
package main import ( "github.com/jinzhu/gorm" _"github.com/jinzhu/gorm/dialects/mysql" "" ) // 1. 定义模型 type User struct { gorm.Model // ID CreateAt UpdateAt DeletedAt Name string Age inte64 } func main(){ // 连接MySQL数据库 db, err := gorm.Open("mysql","root:root1234@(127.0.0.1:13306)/db1?charset=utf8mb4&parseTime=true&loc=Local") if err != nil { panic(err) } defer db.Close() // 2. 把模型与数据库中的表对应起来 db.AutoMigrate(&User{}) // 3.创建(运行一下,数据库里有数据后,注释钓创建,然后执行查询动作) u1 := User{Name:"qimi",Age:18} db.Create(*u1) u2 := User{Name:"jinzhu",Age:20} db.Create(*u2) // 4. 查询 // var user User // 声明模型结构体类型变量user user := new(User) // new和make的区别 db.First(user) fmt.Pringf("user:%#v\n",user) var users []User Db.Debug().Find(&users) // .Debug() 可以打印执行的SQL语句 fmt.Printf("users:%#v\n",users) }
// model.go
package gorm import "time" type Model struct { ID unit `gorm:"primary_key"` CreateAt time.Time UpdateAt time.Time DeletedAt *time.Time `sql:"index"` }
一般查询
// 根据主键查询第一条记录
db.First(&user) // 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;
Where条件
普通SQL查询
// 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 查询
// 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);
提示:通过结构体进行查询时,GORM将会只通过非零值字段查询,如果字段值为0,'',false或者其他零值时,将不会被用于构建查询条件,例如:
db.Where(&User{Name:"jinzhu",Age:0}).Find(&users) // SELECT * FROM users WHERE name = "jinzhu";
可以使用指针或实现Scanner/Valuer接口来避免这个问题。
// 使用指针 type user struct { gorm.Model Name string Age *int } // 使用Scanner/Valuer type User struct { gorm.Model Name string Age sql.NullInt64 // sql.NullInte64 实现了 Scanner/Valuer 接口 }
Not 条件
作用Where类似的情况如下:
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{}).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 条件
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) // SELECT * FROM users WHERE name = 'jinzhu' OR name = 'jinzhu 2';
内联条件
作用与Where查询类似,当内联条件与多个立即执行方法一起使用时,内联条件不会传递给后面的立即执行方法。
立即执行方法(Immediate methods):是指那些会立即生成SQL语句并发送到数据库的方法,他们一般是CURD方法。
额外查询选项
// 为查询SQL添加额外的SQL操作 db.Set("gorm:query_option","FOR UPDATE").First(&user,10) // SELECT * FROM users WHERE id = 10 FOR UPDATE;
FirstOrInit
获取匹配的第一条记录,否则根据给定的条件初始化一个新的对象(仅支持struct和map条件)
// 未找到 db.FirstOrInit(&user,User{Name:"non_existing"}) // user -> User{Name:"non_existing"} // 找到 db.Where(User{Name:"jinzhu"}).FirstOrInit(&user) // user -> User{Id:111,Name:"jinzhu",Age:20} db.FirstOrInit(&user,map[string]interface{}{"name":"jinzhu"}) // user -> User{Id:111,Name:"jinzhu",Age:20}
Attrs
如果记录未找到,将使用参数初始化struct.
// 未找到 db.Where(User{Name:"non_existing"}).Attrs(User{Age:20}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'non_existing'; // user -> User{Name:"non_existing",Age:20} db.Where(User{Name:"non_existing"}).Attrs("age",20).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'non_existing'; // user -> User{Name:"non_existing",Age:20} // 找到 db.Where(User{Name:"jinzhu"}).Attrs(User{Age:30}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'jinzhu'; // user -> User{Id:111,Name:"jinzhu",Age:20}
Assign
不管记录是否找到,都将参数赋值给struct
// 未找到 db.Where(User{Name:"non_existing"}).Assign(User{Age:20}).FirstOrInit(&user) // user -> User{Name:"non_existing",Age:20} // 找到 db.Where(User{Name:"jinzhu"}).Sssign(User{Age:30}).FirstOrInit(&user) // SELECT * FROM USERS WHERE name = 'jinzhu'; // user -> User{Id:111,Name:"jinzhu",Age:30}
FirstOrCreate
获取匹配的第一条记录,否则根据给定的条件创建一个新的记录(仅支持struct和map条件)
//未找到 db.FirstOrCreate(&user,User{Name:"non_existing"}) // INSERT INTO "users" (name) VALUES ("non_existing"); // user -> User{Id:111,Name:"jinzhu"} // 找到 db.Where(User{Name:"jinzhu"}).FirstOrCreate(&user) // user -> User{Id:111,Name:"jinzhu"}
Attrs
如果记录未找到,将使用参数创建struct和记录。
// 未找到 db.Where(User{Name:"non_existing"}).Attrs(User{Age:20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'non_existing'; // INSERT INTO "users" (name,age) VALUES ("non_existing",20); // user -> User{Id:112,Name:"non_existing",Age:20} // 找到 db.Where(User{Name:"jinzhu"}).Attrs(User{Age:30}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'jinzhu'; // user -> User{Id:111,Name:"jinzhu",Age:20}
Assign
不管记录是否找到,都将参数赋值给struct并保存至数据库。
// 未找到 db.Where(User{Name:"non_existing"}).Assign(User{Age:20}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'non_existing'; // INSERT INTO "users" (name, age) VALUES ("non_existing",20); // user -> User{Id:112,Name:"non_existing",Age:20} // 找到 db.Where(User{Name:"jinzhu"}).Assign(User{Age:30}).FirstOrCreate(&user) // SELECT * FROM users WHERE name = 'jinzhu'; // UPDATE users SET age=30 WHERE id=111; // user -> User{Id:111,Name:"jinzhu",Age:30}
高级查询
子查询
基于*gorm.expr的子查询
db.Where("amount > ?",DB.Table("orders").Select("AVG("amount").Where("state = ?","paid").QueryExpr()).Find(&orders) // SELECT * FORM "orders" WHERE "orders"."deleted_at" IS NULL AND (amount > (SELECT AVG(amount) FROM "orders" WHERE (state = 'paid')));
选择字段
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).Row() // SELECT COALESCE(age,'42') FROM users;
排序
Order,指定从数据库中检索出记录的顺序。设置第二参数reorder为true,可以覆盖前面定义的排序条件。
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,指定从数据库检索出的最大记录数。
db.limit(3).Find(&users) // SELECT * FROM users LIMIT 3; // -1 取消Limit 条件 db.Limit(10).Find(&users1).Limit(-1).Find(&users2) // SELECT * FROM users LIMIT 10; (users1) // SELECT * FROM users; (users2)
偏移
Offset,指定开始返回记录钱要跳过的记录数。
db.Offset(3).Find(&users) // SELECT * FROM users OFFSET 3; // -1 取消Offset条件 db.Offset(10).Find(&users1).Offset(-1).Find(&users2) // SELECT * FROM users OFFSET 10; (users1) // SELECT * FROM users;(USERS2)
总数
Count,该model能获取的记录总数。
db.Where("name = ?","jinzhu").Or("name = ?","jinzhu 2").Find(&users).Count(&count) // SELECT * FROM users WHERE name = 'jinzhu' OR '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)
注意:Count必须是链式查询的最后一个操作罗,因为它会覆盖前面的SELECT,但如果里面使用了count时不会覆盖。
Group& Having
rows, err := db.Table("orders").Select("date(created_at) as date, sum(amoount) as total").Group("date(created_at)").Rows() for rows.Next(){ ... }
例子:如何把rows中的数据映射到结构体里
// 使用scan将多条结果扫描进事先准备好的结构体切片中 type Result struct { Date time.Time Total int } var rets []Result // 定义一个切片,用Scan把结果扫描到切片 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)
连接
// Joins,指定连接条件
rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id) for rows.Next(){ ... } db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id") // 多连接及参数 db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?","jinzhu@example.org").Joins("...")
Pluck
Pluck,查询model中的一个列,作为切片,如果想查询多个列,使用scan。
var ages []int64 db.Find(&users).Pluck("age",&ages) var names []string db.Model(&User{}).Pluck("name",&names) db.Table("deleted_users").Pluck("name",&names) // 查询多个字段 db.Select("name,age").Find(&users)
扫描
Scan,扫描结果至一个struct
type Result struct { Name string Age int } var result Result db.Table("users").Select("name,age").Where("name = ?","Antonio").Scan(&result) // 原生SQL Db.Raw("SELECT name, age FROM users WHERE name = ?", "Antonio").Scan(&result)
链式操作相关
链式操作
Method Chaining,Gorm实现了链式操作接口,所以可以把代码写成这样:
// 创建一个查询 tx := db.Where("name = ?", "jinzhu") // 添加更多条件 if someCondition { tx = tx.Where("age = ?", 20) } else { tx = tx.Where("age = ?", 30) } if yetAnotherCondition { tx = tx.Where("active = ?", 1) }
在调用立即执行方法前不会生成Queryyuju ,借助这个特性可以创建一个函数来处理一些通用逻辑。
立即执行方法(Immediate methods):是指那些会立即生成SQL语句并发送到数据库的方法,他们一般是CURD方法。
Create,First,Find,Take,Save,UpdateXXX,Delete,Scan,Row,Rows ...
这是一个基于上面链式方法代码的立即执行方法的例子:
tx.Find(&user)
生成的SQL语句如下:
SELECT * FROM users WHERE name = 'jinzhu' AND age = 30 AND active = 1;
范围
Scopes:是建立在链式操作的基础之上的。
基于它,可以抽取一些通用逻辑,写出更多可重用的函数库。
func AmountGeaterThan1000(db *gorm.DB) *gorm.DB { return db.Where("amount > ?", 1000) } func PaidWithCreditCard(db *gorm.DB) *gorm.DB { return db.Where("pay_mode_sign = ?", "C") } func PaidWithCod(db *gorm.DB) *gorm.DB { return db.Where("pay_mode_sign = ?","C") } 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(AmountGreaterThan1000, PaidWithCreditCard).Fina(&orders) // 查找所有金额大于1000的信用卡订单 db.Scopes(AmountGreaterThan1000,PaidWithCod).Find(&orders) // 查找所有金额大于1000的COD订单 db.Scopes(AmountGreaterThan1000,OrderStatus([]string{"paid","shipped"})).Find(&orders) // 查找所有金额大于1000已付或者已发货的订单
多个立即执行方法
Multiple Immediate Methods,在GORM中使用多个立即执行方法时,后一个立即执行方法会复用前一个立即执行方法的条件(不包括内联条件)
db.Where("name LIKE ?","jinzhu%").Find(&users, "id IN (?)", []int{1,2,3}).Count(&count)
生成的SQL
SELECT * FROM users WHERE name LIKE 'jinzhu%' AND id IN(1,2,3) SELECT count(*) FROM users WHERE name LIKE 'jinzhu%'