无法通过内置方法添加列和创建用户。

huangapple go评论83阅读模式
英文:

Cannot add column and create user by built-in method

问题

我正在尝试使用一个数据库。我被推荐使用Gorm,但是有些方法不起作用,这让我很烦恼。

对于模型,我有以下代码:

type UserModel struct {
    first_name string
    last_name string
}

以下是我的示例代码及其结果。

下面的代码可以工作,但在我的数据库中,表名是user_models

db.Migrator().CreateTable(&UserModel{})

下面的代码不起作用。

err := db.Migrator().AddColumn(&UserModel{}, "first_name")
> failed to look up field with name: first_name

我尝试了下面的代码,它可以工作。

db.Exec("ALTER TABLE user_models ADD first_name varchar(64);")

另一个不起作用的例子是:

user := UserModel{first_name: "Jinzhu", last_name: "name"}
> 没有错误,但插入的是first_name:null和last_name:null

最后,请问有人可以帮我解决这些问题吗?

英文:

I am trying to work with a database. I was recommended to use Gorm, however, it is annoying since some methods are not working.

For model I have:

type UserModel struct {
    first_name string
    last_name string
}

Here is my sample code and results of it.

The below code works but in my database the table name is user_models

 db.Migrator().CreateTable(&UserModel{})

The below code is not working

err := db.Migrator().AddColumn(&UserModel{}, "first_name")

> failed to look up field with name: first_name

I tried this instead and it works

db.Exec("ALTER TABLE user_models ADD first_name varchar(64);")

Another not working

user := UserModel{first_name: "Jinzhu", last_name: "name"}

> Not error but insert first_name:null and last_name:null

Finally, can any help me solve these problems?

答案1

得分: 2

你的两个字段"first_name"和"last_name"(都不符合Go的命名建议)由于以小写字母开头,所以它们是未导出的。这意味着Gorm不会关注这些字段。

我建议你按照以下方式修改,使用Gorm推荐的结构标签来实现你所期望的字段名:

type UserModel struct {
    FirstName string `gorm:"column:first_name"`
    LastName string `gorm:"column:last_name"`
}

更多信息请参考https://gorm.io/docs/models.html#Conventions。

英文:

Your two fields "first_name" and "last_name" (both of which do not follow Go recommendations for naming) are unexported since they start with lowercase letters. This means Gorm does not pay attention to those fields.

I recommend the following which will achieve the field names as you desire using the struct tags recommended by Gorm:

type UserModel struct {
    FirstName string `gorm:"column:first_name"`
    LastName string `gorm:"column:last_name"`
}

See https://gorm.io/docs/models.html#Conventions for more information.

huangapple
  • 本文由 发表于 2021年8月16日 22:58:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/68805044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定