So gorm.Model provides some base properties or fields:
ID uint `json:"-" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `json:"-" sql:"index"`
and you can use it as so
type User struct {
gorm.Model
Name string
Email string `gorm:"type:varchar(100);unique_index"`
Role string `gorm:"size:255"` // set field size to 255
}
So when I was working on my Model Controller(s) for delete (or anything where I needed to compare the ID)
This does not work, give me an error:
c.Ctx.DB.Delete(&models.Address{ID: id})
unknown field 'ID' in struct literal of type github.com/NlaakStudios/PASIT/models".Address
And, this does not work, give me an error:
c.Ctx.DB.Delete(&models.Address{gorm.Model.ID: id})
invalid field name gorm.Model.ID in struct initializer id int
If I remove the gorm.Model and define the field myself in each model ... it works.
type User struct {
ID uint `json:"-" gorm:"primary_key"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `json:"-" sql:"index"`
Name string
Email string `gorm:"type:varchar(100);unique_index"`
Role string `gorm:"size:255"` // set field size to 255
}
How do I access those four base fields?
You're very close in your last example. You can remove the gorm.Model
inheritance from your struct if you want/need (I personally do that for clarity), but to access that value you'd just need to build up your struct a little more. For example...
type Address struct {
gorm.Model
Name string
Email string `gorm:"type:varchar(100);unique_index"`
Role string `gorm:"size:255"` // set field size to 255
}
c.Ctx.DB.Delete(&models.Address{gorm.Model: gorm.Model{ID: id}})
Give that a try and see if that works for you. Alternatively revert to your method without inheriting the gorm.Model
I worked with this: removing package Name 'gorm'
c.Ctx.DB.Delete(&models.Address{Model: gorm.Model{ID: id}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With