我是golang的新手。
这是我的代码:
//main.go
type Project struct {
gorm.Model
Name string
}
type Log struct {
gorm.Model
Project Project
User User
CheckPoint string
Status uint
}
type User struct {
gorm.Model
Name string
Password string
}
//...
db.AutoMigrate(&Project{}, &Log{}, &User{})
我想要:Log.Project ==> Project.ID
Log.User ==> User.ID
但是在数据库日志表中,它是:desc logs;
+-------------+------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| deleted_at | datetime | YES | MUL | NULL | |
| check_point | varchar(255) | YES | | NULL | |
| status | int(10) unsigned | YES | | NULL | |
+-------------+------------------+------+-----+---------+----------------+
我看不到ProjectID或UserID。有指导吗?
先感谢您。
在0825上编辑:
嗨,您好,
也许我需要先解释一下自己。
我需要三个表:项目,用户,日志。
在日志中,它将
which user
和what
记录为which project
。我改变了一点:
type Project struct {
gorm.Model
Name string
}
type User struct {
gorm.Model
Name string
Password string
}
type Log struct {
gorm.Model
ProjectID uint
UserID uint
CheckPoint string // ie: what to record
Status uint // ie: record's status
}
...
db.Debug().Model(&Log{}).AddForeignKey("user_id", "users(id)", "RESTRICT", "RESTRICT")
db.Debug().Model(&Log{}).AddForeignKey("project_id", "projects(id)", "RESTRICT", "RESTRICT")
当我运行代码时,Error 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`logs`, CONSTRAINT `logs_project_id_projects_id_foreign` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`))
Error 1452: Cannot add or update a child row: a foreign key constraint fails (`test`.`#sql-1a0f3_18`, CONSTRAINT `logs_user_id_users_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
我迷路了。
最佳答案
您正在使用has one关系,因此外键将在拥有的模型中(Project&User表应具有log_id
)列。也许您想要的是belongs to关系。
关于go - 更改模型,但数据库未相应更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63565300/