龙空技术网

Gorm基本使用

Nernogno 483

前言:

而今姐妹们对“mysqldrbdmha”可能比较重视,我们都想要知道一些“mysqldrbdmha”的相关内容。那么小编也在网摘上网罗了一些有关“mysqldrbdmha””的相关知识,希望同学们能喜欢,我们一起来学习一下吧!

Gorm安装

go get -u gorm.io/gormgo get -u gorm.io/driver/mysql
连接数据库
    dsn := "username:passwd@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})    if err != nil {        fmt.Println(err)    }    fmt.Println(db)
自动创建表
package mainimport (    "fmt"    "gorm.io/driver/mysql"    "gorm.io/gorm")type User struct {    Id       int64 `gorm:"primary_key" json:"id"` // 设置id为主键    Username string    Password string}func main() {    dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})    if err != nil {        fmt.Println(err)    }    fmt.Println(db)    db.AutoMigrate(User{}) // 自动创建表结构
增删改查
package mainimport (    "fmt"    "gorm.io/driver/mysql"    "gorm.io/gorm")type User struct {    Id       int64 `gorm:"primary_key" json:"id"`    Username string    Password string}func main() {    dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})    if err != nil {        fmt.Println(err)    }    db.Create(&User{        Id:       1,        Username: "test",        Password: "123456",    })    // 新增一条数据,相当于INSERT INTO `test_db`.`users` (`id`,`username`,`password`) VALUES (1, 'test', '123456');    db.Model(User{        Id: 1,    }).Update("username", "test2")    // 更新用户名为test2,相当于 update user set username="test2" where id = 1    db.Delete(&User{Id: 3})   // 删除id是1的用户,相当于delete from user where id = 3    db.Where("username = ?", "test3").Delete(&User{})  // 相当于delete from user where username = "test3"    u := User{Id: 1}    db.First(&u)    fmt.Println(u)  // 查询id是1的用户,只查一条  select * from user where id = 1 limit 1;    users := []User{}    db.Find(&users)    fmt.Println(users)  // 查询user表下的所有书籍, select * from user;}
模型定义
type User struct {    Id           int64 `gorm:"primary_key" json:"id"`    Name         string    CreatedAt    *time.Time `json:"createdAt" gorm:"column:create_at"`    Email        string     `gorm:"type:varchar(100);unique_index"` // 唯一索引    Role         string     `gorm:"size:255"`                       //设置字段的大小为255个字 节    MemberNumber *string    `gorm:"unique;not null"`                // 设置 memberNumber 字段唯一且不为空    Num          int        `gorm:"AUTO_INCREMENT"`                 // 设置 Num字段自增    Address      string     `gorm:"index:addr"`                     // 给Address 创建一个 名字是 `addr`的索引    IgnoreMe     int        `gorm:"-"`                              //忽略这个字段}
一对多
package mainimport (    "encoding/json"    "fmt"    "gorm.io/driver/mysql"    "gorm.io/gorm")/*constraint:OnUpdate:CASCADE 【当User表更新,也会同步给CreditCards】 // 外键约束 OnDelete:SET NULL 【当User中数据被删除时,CreditCard关联设置为 NULL,不删除记录】 */type User struct {    gorm.Model    Username    string       `json:"username" gorm:"column:username"`    CreditCards []CreditCard `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL;"`}type CreditCard struct {    gorm.Model    Number string    UserID uint}func main() {    dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})    if err != nil {        fmt.Println(err)    }    db.AutoMigrate(User{}, CreditCard{})    user := User{        Model:    gorm.Model{},        Username: "lalala",        CreditCards: []CreditCard{            {Number: "0001"},            {Number: "0002"},        },    }    db.Create(&user)  // 为已存在的user添加creditcards,增加操作    u := User{Username: "lalala"}    db.Model(&u).Association("CreditCards").Append([]CreditCard{        {Number: "0003"},    })    strUser, _ := json.Marshal(&u)    fmt.Println(string(strUser))  // Association方法,需要先查询User。根据User中的外键,来查询CreditCard的信息    db.First(&u)    db.Model(&u).Association("CreditCards").Find(&u.CreditCards)    strUser1, _ := json.Marshal(&u)    fmt.Println(string(strUser1))  // preload预加载,在查询 User 时先去获取 CreditCard 的记录    u2 := []User{}    db.Preload("CreditCards").Find(&u2)    strUser2, _ := json.Marshal(&u)    fmt.Println(string(strUser2))}
多对多多对多就是双向一对多Many to Many 会在两个 model 中添加一张连接表。
package mainimport (    "encoding/json"    "fmt"    "gorm.io/driver/mysql"    "gorm.io/gorm"    "time")type Person struct {    ID        uint    Name      string    Addresses []Address `gorm:"many2many:person_addresses;"`  }type Address struct {    ID   uint    Name string}type PersonAddresses struct {    PersonID  int `gorm:"primaryKey"`    AddressID int `gorm:"primaryKey"`    CreatedAt time.Time    DeletedAt gorm.DeletedAt}func main() {    dsn := "root:123456@tcp(127.0.0.1:3306)/test_db?charset=utf8mb4&parseTime=True&loc=Local"    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})    if err != nil {        fmt.Println(err)    }  // 自动创建表结构    db.AutoMigrate(Person{}, Address{})  // 创建数据    persons := Person{        ID:   1,        Name: "qwer",        Addresses: []Address{            {ID: 1, Name: "bdm"},            {ID: 2, Name: "asd"},        },    }    db.Create(&persons)  // Preload查询的两种方式  // 1、获取 name="zhangsan" 用户的地址    persons2 := []Person{}    db.Preload("Addresses").Find(&persons2)    strPerson2, _ := json.Marshal(&persons2)    fmt.Println(string(strPerson2))  // 2、获取 name="zhangsan" 用户的地址    person3 := Person{Name: "zhangsan"}    db.Preload("Addresses").Find(&person3)    strPerson3, _ := json.Marshal(&person3)    fmt.Println(string(strPerson3))}

标签: #mysqldrbdmha