K
K
kireke2021-08-15 15:58:14
go
kireke, 2021-08-15 15:58:14

How to write an array in go gorm in a model?

Please tell me, I have a user model

type User struct {
  ID uint `gorm:"primaryKey;autoIncrement;unique"`
  Email string `gorm:"unique"`
  Password string
  IsAdmin bool `gorm:"default:false"`
  Orders []
}

there should be an array in the Orders field, how to write it correctly? So it gives me an error. I am using Gorm
postgresql database

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
veryoriginalnickname, 2021-08-15
@kireke

Looking with what an array. If with strings, then: Orders [] string. But since we are dealing with a database, I think this will not work. Here we need a relation, like Has Many.
https://gorm.io/docs/has_many.html
For example:

type User struct {
  ID uint `gorm:"primaryKey;autoIncrement;unique"`
  Email string `gorm:"unique"`
  Password string
  IsAdmin bool `gorm:"default:false"`
  Orders []Order `gorm:"constraint:OnDelete:CASCADE;"`
}

type Order struct {
  ID uint `gorm:"primaryKey;autoIncrement;unique"`
  name string `gorm:"notNull;"`
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question