登录
首页 >  Golang >  Go问答

如何从 GO 中的数组将数据输入到 mysql 模型中?

来源:stackoverflow

时间:2024-04-06 23:03:27 177浏览 收藏

小伙伴们有没有觉得学习Golang很有意思?有意思就对了!今天就给大家带来《如何从 GO 中的数组将数据输入到 mysql 模型中?》,以下内容将会涉及到,若是在学习中对其中部分知识点有疑问,或许看了本文就能帮到你!

问题内容

所以,我正在研究这个 mysql 模型,使用 go 和 gorm,用户可以在其中输入数据

`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
}`

我希望我的用户从 department 数组中提供的值中选择一个值并将其存储在我的表中,我该怎么做?


正确答案


您可以为部门定义自定义字符串类型,但您仍然必须显式检查用户提供的字符串是否正确:

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

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>