Mriganka Das
Mriganka Das

Reputation: 21

How can I input data into a mysql model from an array in GO?

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?

Upvotes: 2

Views: 228

Answers (1)

aaronlukacs
aaronlukacs

Reputation: 489

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")
}

Upvotes: 2

Related Questions