英文:
GORM not saving has-many structs
问题
我有一个名为room
的实体,它有关联的members
。当我使用GORM保存room
时,即使切片中有多个成员,也只保存一个成员。
我已经重写了主键为uuid字段,并设置了外键。
我漏掉了什么?
type Room struct {
gorm.Model
UUID string `gorm:"uuid;primaryKey"`
Members []*Member `gorm:"foreignkey:uuid"`
}
type Member struct {
gorm.Model
UUID string `gorm:"uuid;primaryKey"`
RoomUUID string `gorm:"room_uuid"`
UserUUID string `gorm:"user_uuid"`
UserRole string `gorm:"user_role"`
}
// 即使有多个成员,也只保存一个成员。
func (r *Repo) SaveRoom(room *records.Room) error {
return r.DB.Transaction(func(tx *gorm.DB) error {
err := tx.Create(room).Error
if err != nil {
return err
}
return nil
})
}
CREATE TABLE rooms (
id int NOT NULL UNIQUE AUTO_INCREMENT,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
uuid VARCHAR(36) NOT NULL UNIQUE PRIMARY KEY
);
CREATE TABLE members (
id int NOT NULL UNIQUE AUTO_INCREMENT,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
uuid VARCHAR(36) NOT NULL UNIQUE PRIMARY KEY,
room_uuid VARCHAR(36) NOT NULL,
user_uuid VARCHAR(36) NOT NULL,
user_role VARCHAR(36) NOT NULL
);
英文:
I have a room
entity that has associated members
. When I save the room
using GORM, only one member gets saved even if the slice has multiple members.
I've overwritten the primary key to be the uuid field and set the foreign keys.
What am I missing?
type Room struct {
gorm.Model
UUID string `gorm:"uuid;primaryKey"`
Members []*Member `gorm:"foreignkey:uuid"`
}
type Member struct {
gorm.Model
UUID string `gorm:"uuid;primaryKey"`
RoomUUID string `gorm:"room_uuid"`
UserUUID string `gorm:"user_uuid"`
UserRole string `gorm:"user_role"`
}
// only saves one member even if there are more.
func (r *Repo) SaveRoom(room *records.Room) error {
return r.DB.Transaction(func(tx *gorm.DB) error {
err := tx.Create(room).Error
if err != nil {
return err
}
return nil
})
}
CREATE TABLE rooms (
id int NOT NULL UNIQUE AUTO_INCREMENT,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
uuid VARCHAR(36) NOT NULL UNIQUE PRIMARY KEY
);
CREATE TABLE members (
id int NOT NULL UNIQUE AUTO_INCREMENT,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
uuid VARCHAR(36) NOT NULL UNIQUE PRIMARY KEY,
room_uuid VARCHAR(36) NOT NULL,
user_uuid VARCHAR(36) NOT NULL,
user_role VARCHAR(36) NOT NULL
);
答案1
得分: 1
这是因为你的外键关联是错误的。应该是gorm:"foreignKey:room_uuid;references:uuid"
,而不是gorm:"foreignkey:uuid"
。此外,你可能需要手动删除之前创建的错误外键。
另一个问题是你同时使用了gorm.Model
和UUID
,gorm.Model
已经有一个ID
字段了。如果没有必要,我建议只使用一个主键。
英文:
This is because your foreign key association is wrong. This should be gorm:"foreignKey:room_uuid;references:uuid"
instead of gorm:"foreignkey:uuid"
. Additinally you might need to manually delete the wrong foreign key created previously.
Another point is you are using gorm.Model
which has an ID
field and additionally you are using UUID
. My suggestion is to use one primary key instead of two if it's not necessary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论