Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access gorm.Model.ID?

Tags:

go

model

go-gorm

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?

like image 543
NlaakALD Avatar asked Dec 17 '22 21:12

NlaakALD


2 Answers

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

like image 89
sebito91 Avatar answered Jan 11 '23 16:01

sebito91


I worked with this: removing package Name 'gorm'

c.Ctx.DB.Delete(&models.Address{Model: gorm.Model{ID: id}})
like image 40
Danielzz Avatar answered Jan 11 '23 14:01

Danielzz