go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.66k stars 3.92k forks source link

what is the diff of gorm tag - and -:all #7059

Open zrss opened 3 months ago

zrss commented 3 months ago

what is the diff of gorm tag - and -:all

https://gorm.io/docs/models.html#Fields-Tags

the above doc explains the - gorm tag

so i doubt about the diff between - and -:all, and do a simple experiment.

step 1, create the user model.

package main

import (
    "fmt"
    "gorm.io/gorm"
    "time"

    "github.com/sirupsen/logrus"
    "gorm.io/driver/postgres"
    "gorm.io/gorm/logger"
)

type User struct {
    ID   uint
    Name string
    Age  int
}

func main() {
    gormLogger := logger.New(
        logrus.WithField("Component", "gorm"),
        logger.Config{
            SlowThreshold:             time.Second,
            LogLevel:                  logger.Warn,
            IgnoreRecordNotFoundError: true,
            ParameterizedQueries:      true,
            Colorful:                  false,
        },
    )

    dbArgs := ...

    db, err := gorm.Open(postgres.Open(dbArgs), &gorm.Config{Logger: gormLogger})
    if err != nil {
        logrus.Fatal(err)
    }

    err = db.AutoMigrate(&User{})
    if err != nil {
        logrus.Warning(err)
    }
}

currently, the result in postgres db shows that the Age column is int8.

step 2, change the Age field of User model from int to string type, and add only the gorm tag -.

package main

import (
    "fmt"
    "gorm.io/gorm"
    "time"

    "github.com/sirupsen/logrus"
    "gorm.io/driver/postgres"
    "gorm.io/gorm/logger"
)

type User struct {
    ID   uint
    Name string
    Age  string `gorm:"-"`
}

func main() {
    gormLogger := logger.New(
        logrus.WithField("Component", "gorm"),
        logger.Config{
            SlowThreshold:             time.Second,
            LogLevel:                  logger.Warn,
            IgnoreRecordNotFoundError: true,
            ParameterizedQueries:      true,
            Colorful:                  false,
        },
    )

    dbArgs := ...

    db, err := gorm.Open(postgres.Open(dbArgs), &gorm.Config{Logger: gormLogger})
    if err != nil {
        logrus.Fatal(err)
    }

    err = db.AutoMigrate(&User{})
    if err != nil {
        logrus.Warning(err)
    }
}

but the result in postgres db shows that the Age column is still int8, nothing happen. so it seems gorm - tag also ignore migrate either.

step 3, remove the gorm - tag, and re-run above code, results that the Age column changed to the text type

The document you expected this should be explained

Expected answer

could someone explain in detail about the diff between - and -:all tag, or give some demo code to illustrate it may be more understandable.