Describe the feature

I'd love to have a "read-only" fields, i.e. such that are ignored during migration and during writes, but respected when reading. Similarly to "-:all" and "-:migrate", there could be a "-:write".

type User struct {
  Name string `gorm:"-"`            // ignore this field when write and read with struct
  Name string `gorm:"-:write"`    // ignore this field when write and migrate with struct
  Name string `gorm:"-:all"`        // ignore this field when write, read and migrate with struct
  Name string `gorm:"-:migration"`  // ignore this field when migrate with struct
}

Motivation

Use case are models, where one or more fields do not "physically" exist as a column, but are populated by the database during querying. Here is an example:

// model declaration
type LeaderboardEntry struct {
    ID     uint          `gorm:"primary_key; size:32"`
    UserID string        `gorm:"not null"`
    Total  time.Duration `gorm:"not null"`
    Key    string        `gorm:"size:255"`
    Rank   uint          `gorm:"-:write"`
}

// query
var entries []*LeaderboardEntry
r.db.
    Table("leaderboard_entries").
    Select("*, rank() over (partition by \"key\" order by total desc) as \"rank\"").
    Find(&entries)

I would want the rank field to be read by Gorm, but not be written during inserts, because it doesn't exist as a column. A workaround is to use a "wrapper" struct, as described here, but I don't like that approach a lot.

Related Issues

  • https://github.com/go-gorm/gorm/issues/5284
  • https://github.com/go-gorm/gorm/issues/3089

Comment From: System-Glitch

You can use the following tag : gorm:"->;-:migration".

Comment From: muety

Will try that, thank you!