6

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?

Sascha Frinken
  • 3,134
  • 1
  • 24
  • 27
NlaakALD
  • 377
  • 2
  • 6
  • 16
  • 1
    Have you looked through the [docs](http://gorm.io/docs/delete.html)? – Havelock Jul 26 '18 at 08:52
  • 2
    Possible duplicate of [Initialize embedded struct in Go](https://stackoverflow.com/questions/12537496/initialize-embedded-struct-in-go) – Peter Jul 26 '18 at 09:33

3 Answers3

8

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

sebito91
  • 514
  • 4
  • 7
  • This worked, weird way of referencing. yes, I ended up just removing gorm.Model and declaring the ID,, created and updated fields to all objects. Thank You! – NlaakALD Jul 28 '18 at 00:42
7

I worked with this: removing package Name 'gorm'

c.Ctx.DB.Delete(&models.Address{Model: gorm.Model{ID: id}})
Danielzz
  • 81
  • 1
  • 3
-1

looks like this is an interesting question - but of category 'selfmade problem':

what about

c.Ctx.DB.Delete(&model.Address{}, id)

then you can keep the benefits (or not - depends on taste) of gorm.Model

rene paulokat
  • 302
  • 1
  • 7