zl程序教程

您现在的位置是:首页 >  其它

当前栏目

Gorm-定义模型字段和标签(二)

模型 定义 标签 字段 Gorm
2023-06-13 09:18:49 时间

示例代码

以下是使用Gorm定义模型字段和标签的示例代码:

package main

import (
    "fmt"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "time"
)

type User struct {
    ID        uint   `gorm:"primaryKey"`
    Name      string `gorm:"column:username;size:100;not null"`
    Age       int    `gorm:"not null"`
    Email     string `gorm:"unique;not null"`
    Avatar    []byte
    CreatedAt time.Time `gorm:"autoCreateTime"`
    UpdatedAt time.Time `gorm:"autoUpdateTime"`
}

func main() {
    // 连接MySQL数据库
    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 {
        panic("Failed to connect to database!")
    }

    // 自动迁移模型
    err = db.AutoMigrate(&User{})
    if err != nil {
        panic("Failed to migrate model!")
    }

    // 插入数据
    user := User{
        Name:      "John",
        Age:       30,
        Email:     "john@example.com",
        Avatar:    []byte("avatar"),
        CreatedAt: time.Now(),
        UpdatedAt: time.Now(),
    }
    result := db.Create(&user)
    if result.Error != nil {
        panic("Failed to create user!")
    }
    fmt.Println("User created successfully!")
}

在上述示例代码中,我们首先定义了一个名为User的结构体,并为每个字段设置了不同的标签。接着,我们通过调用AutoMigrate方法,自动将User模型迁移到MySQL数据库中。最后,我们插入了一条用户记录,并通过Create方法将其保存到数据库中。Gorm-定义模型字段和标签(一)