go gorm 查询

  1. 定义model
package mysqltest

import (
	"errors"
	"fmt"

	"gorm.io/gorm"
)

type Product struct {
	gorm.Model
	ID    uint    `gorm:"primarykey"`
	Name  string  `gorm:"column:name"`
	Price float64 `gorm:"column:price_value"`
	Test  string  `gorm:"-"`
}

type Tabler interface {
	TableName() string
}

// 修改表名
func (recv Product) TableName() string {
	return "product"
}

// 钩子
func (recv *Product) BeforeCreate(tx *gorm.DB) (err error) {
	if recv.Name == "haha" {
		fmt.Println("不合法哈")
		return errors.New("不合法哈")
	} else {
		return nil
	}
}

  1. helper
package mysqltest

import (
	"fmt"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

var db *gorm.DB

func Initdb() {
	dsn := "ellis:ellis@tcp(192.168.214.134:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
}

func Create(value interface{}) {
	d := db.Create(value)
	fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}

func InitTable(table interface{}) {
	db.AutoMigrate(table)
}

// 根据选择的字段插入
func CreateBySelectFields(fields []string, value interface{}) {
	db.Select(fields).Create(value)
}

// 批量插入
func CreateMulti(value interface{}) {
	d := db.Create(value)
	fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}

// 批量插入
func CreateBatch(value interface{}) {
	d := db.CreateInBatches(value, 100)
	fmt.Printf("d.RowsAffected: %v\n", d.RowsAffected)
}

// 忽略钩子
func CreateIgnoreHook(value interface{}) {
	db.Session(&gorm.Session{SkipHooks: true}).Create(value)
}

// 通过map创建
func CreateByMap(value map[string]interface{}, model interface{}) {
	db.Model(model).Create(value)
}

// 冲突啥也不做
func DoNothingWhenInsert(value interface{}) {
	db.Clauses(clause.OnConflict{DoNothing: true}).Create(value)
}

// 通过主键查找
func FindByKey(value interface{}) {
	db.Find(value, 1)
}

// 查找后映射到map类型
func FindAndConvertToMap(value interface{}, result *map[string]interface{}) {
	db.Model(value).First(result)
}

// 多主键查找
func FindByMultiKey(value interface{}, keys []int) {
	db.Find(value, keys)
}

// 条件查找
func FindByCondition(value interface{}) {
	db.Where("name=?", "haha").Order("id desc").Find((value))
}

// struct 查找,会忽略0值,例如传入ID=0,这个ID=0不会作为查询条件
func FindByStruct(value interface{}, condition interface{}) {
	db.Where(condition).Find(value)
}

// 指定结构体查询字段
func FindByStructWithReturnFields(value interface{}, condition interface{}, returnFields ...string) {
	db.Where(condition, returnFields).Order("id desc").Find(value)
}

  1. main
package main

import (
	"ellis/mysqltest"
	"fmt"
)

func main() {
	mysqltest.Initdb()
	// 创建数据库
	mysqltest.InitTable(&mysqltest.Product{})

	var value mysqltest.Product

	mysqltest.FindByKey(&value)

	fmt.Printf("value: %v\n", value)

	// 映射到map
	result := map[string]interface{}{}

	mysqltest.FindAndConvertToMap(mysqltest.Product{}, &result)
	fmt.Printf("result: %v\n", result)

	// 多主键查找
	var products1 []mysqltest.Product

	mysqltest.FindByMultiKey(&products1, []int{1, 2, 3})

	for _, v := range products1 {
		fmt.Printf("v: %v\n", v)
	}

	// 条件查找
	var products2 []mysqltest.Product

	mysqltest.FindByCondition(&products2)

	for _, v := range products2 {
		fmt.Printf("v: %v\n", v)
	}
	// struct 查找
	var products3 []mysqltest.Product
	// ID 为0的被忽略
	produce := mysqltest.Product{Name: "haha", ID: 0}
	mysqltest.FindByStruct(&products3, produce)
	for _, v := range products3 {
		fmt.Printf("v: %v\n", v)
	}
	// map 查找
	var products4 []mysqltest.Product
	// ID 为0的被忽略
	produce1 := map[string]interface{}{"Name": "haha", "ID": 0}
	mysqltest.FindByStruct(&products4, produce1)
	for _, v := range products4 {
		fmt.Printf("v: %v\n", v)
	}

	// struct 查找,可以设置使用的struct的key
	var products []mysqltest.Product
	// ID 为0的被忽略
	produce2 := mysqltest.Product{Name: "haha"}
	mysqltest.FindByStructWithReturnFields(&products, produce2, "name", "id")
	for _, v := range products {
		fmt.Printf("v: %v\n", v)
	}
}

https://gorm.io/docs/query.html

https://gorm.io/docs/advanced_query.html

你可能感兴趣的:(GO,golang,开发语言,后端)