英文:
How can I input data into a mysql model from an array in GO?
问题
所以,我正在使用GO和GORM开发这个MySQL模型,用户可以输入他们的数据。
package table
import (
// "gorm.io/driver/mysql"
"gorm.io/gorm"
)
var Department = []string{"计算机科学", "工程", "医学科学"}
type Account struct {
gorm.Model
Accountname string `json:"name"` //AccountName
AccontNumber int64 `json:"number"` //AccountNumber Text(40)
//需要用户从Department数组中选择一个值
}
我希望用户可以从提供的Department数组中选择一个值,并将其存储在我的表中,我该如何做到这一点?
英文:
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
得分: 2
你可以为部门定义一个自定义字符串类型,但你仍然需要显式地检查用户提供的字符串是否正确:
type DepartmentName string
const (
DepartmentComputerScience DepartmentName = "计算机科学"
DepartmentNameEngineering DepartmentName = "工程"
DepartmentNameMedicalScience DepartmentName = "医学科学"
)
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("无效的部门")
}
英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论