2

So, I'm working on this mysql model Using GO and GORM where the user can input their data

`package table

import (
    //"gorm.io/driver/mysql"
    "gorm.io/gorm"
)

var Department = []string{"Computer Science", "Engineering", "Medical Science"}

type Account struct {
    gorm.Model
    Accountname  string `json:"name"`    //AccountName
    AccontNumber int64  ` json:"number"` //AccountNumber        Text(40)
   //need users to select one of the values from the Department Array
}`

I want my user to select a value from the ones provided in the Department array and store it in my table, how can I go about doing it?

1
  • 1
    you can try gorm:"type:enum('published', 'pending', 'deleted');default:'pending'" Commented May 17, 2022 at 13:50

1 Answer 1

2

You can define a custom string type for departments, but you still will have to explicitly check that the user provided string is correct:

type DepartmentName string

const (
    DepartmentComputerScience DepartmentName "Computer Science"
    DepartmentNameEngineering DepartmentName "Engineering"
    DepartmentNameMedicalScience DepartmentName "Medical Science"

)
var DepartmentsMap = map[DepartmentName]bool{
    DepartmentComputerScience: true, 
    DepartmentNameEngineering: true, 
    DepartmentNameMedicalScience: true,
}


type Account struct {
    gorm.Model
    Accountname  string         `json:"name"`    //AccountName
    AccontNumber int64          ` json:"number"` //AccountNumber        Text(40)
    Department   DepartmentName `json:"department"`
}

func (d DepartmentName) Valid() error {
    if _, ok := DepartmentsMap[d]; ok {
        return nil
    }
    return errors.New("invalid department")
}
Sign up to request clarification or add additional context in comments.

1 Comment

i made a syntax error, you should access the element from the map like DepartmentsMap[d] instead of the (). i edited my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.