Description

There are two bugs:

My UserGame table has a Describe field, but it's not mapped to the database table. After running the code, the field doesn't exist in the database table. Furthermore, the Game table doesn't have an auto-increment start value set, yet when inserting data, it starts at 1001. (This setting only exists in the User table; I'm not sure why it also exists in the Game table.)

Table structure

package model

import (
    "time"

    "github.com/shopspring/decimal"
)

type User struct {
    ID         uint      `gorm:"primaryKey;autoIncrement" json:"id"`
    Name       string    `gorm:"type:varchar(32);not null" json:"name"`
    Avatar     string    `gorm:"type:varchar(255);not null" json:"avatar"`
    Sex        string    `gorm:"type:varchar(1);not null" json:"sex"`
    Hot        uint      `gorm:"default:0" json:"hot"`
    Audio      *string   `gorm:"type:varchar(255);null" json:"audio"`
    OpenId     string    `gorm:"type:varchar(128);not null;unique" json:"openid"`
    IsProvider bool      `gorm:"default:false" json:"is_provider"`
    Games      []Game    `gorm:"many2many:user_games" json:"games"`
    CreatedAt  time.Time `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt  time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}

type Game struct {
    ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
    Icon      string    `gorm:"type:varchar(255);not null" json:"icon"`
    Name      string    `gorm:"type:varchar(32);not null" json:"name"`
    Users     []User    `gorm:"many2many:user_games" json:"users"`
    CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt time.Time `gorm:"autoUpdateTime" json:"updated_at"`
}

type UserGame struct {
    ID        uint      `gorm:"primaryKey;autoIncrement" json:"id"`
    UserID    uint      `gorm:"not null;index;uniqueIndex:idx_user_game;constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"user_id"`
    GameID    uint      `gorm:"not null;index;uniqueIndex:idx_user_game;constraint:OnUpdate:CASCADE,OnDelete:CASCADE" json:"game_id"`
    Describe  string    `gorm:"type:text;not null" json:"describe"`
    CreatedAt time.Time `gorm:"autoCreateTime" json:"created_at"`
}

type Order struct {
    ID          uint             `gorm:"primaryKey;autoIncrement" json:"id"`
    OrderNumber string           `gorm:"type:varchar(64);not null;uniqueIndex" json:"order_number"`
    FromUserID  uint             `gorm:"not null;index" json:"from_user_id"`
    ToUserID    uint             `gorm:"not null;index" json:"to_user_id"`
    GameID      uint             `gorm:"not null;index" json:"game_id"`
    UnitCount   uint             `gorm:"not null" json:"unit_count"`
    TotalPrice  *decimal.Decimal `gorm:"type:decimal(9,2);not null" json:"total_price"`
    Remark      string           `gorm:"type:text;not null" json:"remark"`
    Status      string           `gorm:"type:varchar(16);not null;default:'pending'" json:"status"`
    CreatedAt   time.Time        `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt   time.Time        `gorm:"autoUpdateTime" json:"updated_at"`
    FromUser *User `gorm:"foreignKey:FromUserID" json:"from_user,omitempty"`
    ToUser   *User `gorm:"foreignKey:ToUserID" json:"to_user,omitempty"`
    Game     *Game `gorm:"foreignKey:GameID" json:"game,omitempty"`
}

type Product struct {
    ID          uint             `gorm:"primaryKey;autoIncrement" json:"id"`
    UserID      uint             `gorm:"not null;index" json:"user_id"`
    GameID      uint             `gorm:"not null;index" json:"game_id"`
    Name        string           `gorm:"type:varchar(64);not null" json:"name"`
    Description string           `gorm:"type:text;not null" json:"description"`
    Price       *decimal.Decimal `gorm:"type:decimal(9,2);not null" json:"price"`
    ChargeType  string           `gorm:"type:varchar(16);not null" json:"charge_type"`
    CreatedAt   time.Time        `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt   time.Time        `gorm:"autoUpdateTime" json:"updated_at"`
    User        *User            `gorm:"foreignKey:UserID" json:"user,omitempty"`
    Game        *Game            `gorm:"foreignKey:GameID" json:"game,omitempty"`
}

type Rank struct {
    ID        uint             `gorm:"primaryKey;autoIncrement" json:"id"`
    GameID    uint             `gorm:"not null;index" json:"game_id"`
    Name      string           `gorm:"type:varchar(32);not null" json:"name"`
    Price     *decimal.Decimal `gorm:"type:decimal(9,2);not null" json:"price"`
    CreatedAt time.Time        `gorm:"autoCreateTime" json:"created_at"`
    UpdatedAt time.Time        `gorm:"autoUpdateTime" json:"updated_at"`
    Game      *Game            `gorm:"foreignKey:GameID" json:"game,omitempty"`
}

Automatic Migration

package mysql

import (
    "fmt"
    "log"
    "net/url"
    "os"
    "pupue-sportsclub/model"
    "time"

    "github.com/spf13/viper"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "gorm.io/gorm/logger"
)

var MySqlClient *gorm.DB

func InitMySqlClient() *gorm.DB {
    db, err := gorm.Open(mysql.Open(fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=%s", viper.GetString("mysql.username"), viper.GetString("mysql.password"), viper.GetString("mysql.host"), viper.GetString("mysql.port"), viper.GetString("mysql.database"), viper.GetString("mysql.charset"), url.QueryEscape(viper.GetString("mysql.loc")))), &gorm.Config{
        Logger: logger.New(
            log.New(os.Stdout, "\r\n", log.LstdFlags),
            logger.Config{
                SlowThreshold:             time.Second,   // Slow SQL threshold
                LogLevel:                  logger.Silent, // Log level
                IgnoreRecordNotFoundError: true,          // Ignore ErrRecordNotFound error for logger
                ParameterizedQueries:      true,          // Don't include params in the SQL log
                Colorful:                  false,         // Disable color
            },
        ),
    })
    if err != nil {
        panic("fail to connect mysql database, err: " + err.Error())
    }
    db.Set("gorm:table_options", "AUTO_INCREMENT=1001").AutoMigrate(&model.User{})
    db.AutoMigrate(&model.Game{}, &model.UserGame{}, &model.Order{}, &model.Product{}, &model.Rank{})
    MySqlClient = db
    return db
}

func GetMySqlClient() *gorm.DB {
    return MySqlClient
}

UserGame table

Image

Game table

Image

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking