Gorm: How to determine final database field name

Created on 9 Jul 2018  ·  4Comments  ·  Source: go-gorm/gorm

Currently, we define type struct model. I have a use case and I would like know what is the field name used in database.

type User struct {
    CreatedAt time.Time
}

Final field name will be created_at but I can't found no method in Gorm to found this.

gorm_v1 question

All 4 comments

  1. created_at is automatic CamelCase->snake_case conversion that gorm performs.
  2. gorm.Model uses CreatedAt as one of it's fields.
  3. If you do not embed it on User — you will not have an issue.

Also, look at how you can use annotations to set the column name yourself:

CreatedAt time.Time `sql:"column:creation_date;"`

I would like determine (with a internal Gorm method), the field name generated.

CreatedAt time.Time `sql:"column:creation_date;"`
UpdatedAt time.Time

Field names given will be creation_date and updated_at.

Your internal method to determine final field name to use in database is it public ?

I don't know if you found the answer or not. but this what I found.

You can use Scope For example:

userScope := db.NewScope(User{})
createdAtField, ok := userScope.FieldByName("CreatedAt")
fieldName := createdAtField.DBName

This issue will be automatically closed because it is marked as GORM V1 issue, we have released the public testing GORM V2 release and its documents https://v2.gorm.io/docs/ already, the testing release has been used in some production services for a while, and going to release the final version in following weeks, we are still actively collecting feedback before it, please open a new issue for any suggestion or problem, thank you

Also check out https://github.com/go-gorm/gorm/wiki/GORM-V2-Release-Note-Draft for how to use the public testing version and its changelog

Was this page helpful?
0 / 5 - 0 ratings

Related issues

izouxv picture izouxv  ·  3Comments

fieryorc picture fieryorc  ·  3Comments

easonlin404 picture easonlin404  ·  3Comments

rfyiamcool picture rfyiamcool  ·  3Comments

leebrooks0 picture leebrooks0  ·  3Comments