英文:
gorm does not generate string columns
问题
我正在尝试使用gorm将我的模型迁移到PostgreSQL数据库。但是gorm在表中不生成字符串列。以下是我的模型:
type Task struct {
gorm.Model
Answer float64
TaskParts []TaskPart `gorm:"foreignKey:TaskId"`
}
type TaskPart struct {
gorm.Model
Answer float64
Items []BackpackTaskItem `gorm:"foreignKey:TaskPartId"`
TaskId uint
}
type BackpackTaskItem struct {
gorm.Model
Weight float64
Price float64
IsFixed bool
TaskPartId uint
}
type TaskUserSolution struct {
gorm.Model
TaskPartId uint
TaskPart TaskPart `gorm:"foreignKey:TaskPartId;references:ID"`
UserId uint
User User `gorm:"foreignKey:UserId;references:ID"`
}
type User struct {
gorm.Model
username string
password string
}
然后我运行了这行代码:
err = db.AutoMigrate(&Task{}, &TaskPart{}, &BackpackTaskItem{}, &TaskUserSolution{}, &User{})
它没有给我任何错误,并成功创建了表。但是对于用户表,没有字符串列(username
和password
)。它只有gorm列(id、created_date、deleted_date、updated_date)。
这是一个错误还是我做错了什么?
我的go build是最新的。我尝试给其他模型添加字符串字段,但它也没有创建字符串列。
我完全删除了表,但没有帮助。
go.mod中的gorm版本:
gorm.io/driver/postgres v1.4.5
gorm.io/gorm v1.24.2
英文:
I'm trying to migrate my models to PostgreSQL database using gorm. But gorm does not generate string columns in tables. Here are my models:
type Task struct {
gorm.Model
Answer float64
TaskParts []TaskPart `gorm:"foreignKey:TaskId"`
}
type TaskPart struct {
gorm.Model
Answer float64
Items []BackpackTaskItem `gorm:"foreignKey:TaskPartId"`
TaskId uint
}
type BackpackTaskItem struct {
gorm.Model
Weight float64
Price float64
IsFixed bool
TaskPartId uint
}
type TaskUserSolution struct {
gorm.Model
TaskPartId uint
TaskPart TaskPart `gorm:"foreignKey:TaskPartId;references:ID"`
UserId uint
User User `gorm:"foreignKey:UserId;references:ID"`
}
type User struct {
gorm.Model
username string
password string
}
Then I run this line of code:
err = db.AutoMigrate(&Task{}, &TaskPart{}, &BackpackTaskItem{}, &TaskUserSolution{}, &User{})
It does not give me any errors and successfully creates tables. But for table users there are no string columns (username
and password
). It has only gorm coumns (id, created_date, deleted_date, updated_date).
Is this a bug or am I doing something wrong?
My go build is up to date. I tried adding string fields to other models, but it did not create string columns either.
I completely dropped tables, but it did not help.
Gorm versions from go.mod:
gorm.io/driver/postgres v1.4.5
gorm.io/gorm v1.24.2
答案1
得分: 3
使用小写字母作为变量名的开头可以使其成为私有变量,在声明变量时使用大写字母作为变量名的开头。
例如:
type User struct {
gorm.Model
Username string
Password string
}
你将得到如下的表格:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论