0

I'm trying to follow Gorm's documentation to create a generated field, defined by a function:

type Foo struct {
    ID            int64  `json:"id"`
    AmountOfBars  string `json:"amount_of_bars" gorm:"default:amount_of_bars()"`
}

type RelatedBar struct {
    FooId int64 `json:"foo_id"`
}

However, I don't understand where and how to define amount_of_bars, so I'll be able to return the amount of the RelatedBar related rows.

idik
  • 872
  • 2
  • 10
  • 19
  • Looking at the `uuid_generate_v3()` function from the documentation, the `amount_of_bars()` function should be a function defined in your database. – Emin Laletovic Aug 13 '21 at 20:39

2 Answers2

0

You don't define such a function in Go, you define it in your database via CREATE FUNCTION. See https://www.postgresql.org/docs/9.1/sql-createfunction.html.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • Sounds good, is it possible to add this function programmatically through golang's pq or gorm? I don't want anything to be configured manually on my DB... – idik Aug 14 '21 at 05:50
  • @idik You can use `Exec` to run arbitrary SQL against your database. – user229044 Aug 14 '21 at 11:23
0
type User struct {
ID        int    `json:"id" gorm:"autoIncrement; primaryKey"`
Username  string `json:"username" `
FirstName string `json:"first_name" `
LastName  string `json:"last_name" `
FullName  string `json:"full_name" `
Name      string `json:"name" `
AvatarURL string `json:"avatar_url" gorm:"default:'http://www.google/.com'" `

CreatedAt int // Set to current time if it is zero on creating
UpdatedAt int // Set to current unix seconds on updating or if it is zero on creating
Deleted   gorm.DeletedAt

}