gorm系列-查詢


Gorm查詢

一般查詢

// 根據主鍵查詢第一條記錄
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;
package main

import (
	"database/sql"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

//1. 定義模型
type User struct {
	ID int64
	//Name *string  `gorm:"default:'zisefeizhu'"`
	Name sql.NullString `gorm:"default:'zisefeizhu'"`
	Age byte
}

func main() {
	//2. 連接Mysql數據庫
	db, err := gorm.Open("mysql","root:123456@tcp(127.0.0.1:3306)/db?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		panic(err)
	}
	defer db.Close()
	//3. 把模型與數據庫中的表對應起來
	db.AutoMigrate(&User{})

	//4. 創建結構體實例
	//u := User{Name: sql.NullString{"", false}, Age: 60}
	//fmt.Println(db.NewRecord(&u)) // 主鍵為空返回`true`
	//db.Debug().Create(&u)   // 在數據庫中創建一條user記錄
	//fmt.Println(db.NewRecord(u)) // 創建`user`后返回`false`

	//查詢
	//var user User   //聲明模型結構體變量類型user (文件夾A)
	//db.First(&user)  //(文件夾B)
	//user:main.User{ID:1, Name:sql.NullString{String:"zisefeizhu", Valid:true}, Age:0x1e}
	user := new(User)
	db.First(user)
	fmt.Printf("user:%#v\n",user)
	//user:&main.User{ID:1, Name:sql.NullString{String:"zisefeizhu", Valid:true}, Age:0x1e}

	//查詢所有記錄
	var users []User
	//users := make([]User, 10)
	db.Find(&users)
	fmt.Printf("user:%#v\n",users)
}

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';
//查詢where記錄
	var users []User

	db.Where("name = ?", "zisefeizhu ").Find(&users)
	fmt.Printf("user:%#v\n",users)
Struch & 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.NullInt64 實現了 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{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條件

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查詢類似,當內聯條件與多個立即執行方法一起使用時, 內聯條件不會傳遞給后面的立即執行方法。

// 根據主鍵獲取記錄 (只適用於整形主鍵)
db.First(&user, 23)
//// SELECT * FROM users WHERE id = 23 LIMIT 1;
// 根據主鍵獲取記錄, 如果它是一個非整形主鍵
db.First(&user, "id = ?", "string_primary_key")
//// SELECT * FROM users WHERE id = 'string_primary_key' LIMIT 1;

// Plain 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;

額外查詢選項

// 為查詢 SQL 添加額外的 SQL 操作
db.Set("gorm:query_option", "FOR UPDATE").First(&user, 10)
//// SELECT * FROM users WHERE id = 10 FOR UPDATE;

FirstOrInit

獲取匹配的第一條記錄,否則根據給定的條件初始化一個新的對象 (僅支持 struct 和 map 條件)

//查詢FirstOrInit記錄
var user User
db.FirstOrInit(&user,User{Name: "小王子"})
fmt.Printf("user:%#v\n",user)
//user:main.User{ID:0, Name:"小王子", Age:0x15}
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"}).Assign(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: 112, Name: "non_existing"}

// 找到
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").SubQuery()).Find(&orders)
// SELECT * FROM "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).Rows()
//// 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 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)

注意:Count 必須是鏈式查詢的最后一個操作 ,因為它會覆蓋前面的 SELECT,但如果里面使用了 count 時不會覆蓋

Group & Having
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)
連接

Joins,指定連接條件

rows, err := db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Rows()
for rows.Next() {
  ...
}

db.Table("users").Select("users.name, emails.email").Joins("left join emails on emails.user_id = users.id").Scan(&results)

// 多連接及參數
db.Joins("JOIN emails ON emails.user_id = users.id AND emails.email = ?", "jinzhu@example.org").Joins("JOIN credit_cards ON credit_cards.user_id = users.id").Where("credit_cards.number = ?", "411111111111").Find(&user)

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)

var results []Result
db.Table("users").Select("name, age").Where("id > ?", 0).Scan(&results)

// 原生 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)
}

在調用立即執行方法前不會生成Query語句,借助這個特性你可以創建一個函數來處理一些通用邏輯。

立即執行方法

Immediate methods ,立即執行方法是指那些會立即生成SQL語句並發送到數據庫的方法, 他們一般是CRUD方法,比如:

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,Scope是建立在鏈式操作的基礎之上的。
基於它,你可以抽取一些通用邏輯,寫出更多可重用的函數庫。

func AmountGreaterThan1000(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).Find(&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%'


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM