我有这三种型号
type Store struct {
Id int `gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL;UNIQUE"`
Store_Id string `gorm:"type:varchar(190)";"NOT NULL";"UNIQUE"`
}
type File struct {
Id int `gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL;UNIQUE"`
Organization_Id string `gorm:"type:varchar(190)";"NOT NULL"`
File_Id string `gorm:"type:varchar(190)";"NOT NULL";"UNIQUE"`
}
type File_Store_Linker struct {
Id int `gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL"`
File_Id string `gorm:"type:varchar(190)";"NOT NULL"`
Store_Id string `gorm:"type:varchar(190)";"NOT NULL"`
File_Type string `gorm:"type:varchar(50)";"NOT NULL"`
}
我想在File_Storage_Linker结构中创建这样的外键。
create table file_store_linker (
id INT NOT NULL AUTO_INCREMENT,
file_id VARCHAR(190) NOT NULL,
store_id VARCHAR(190) NOT NULL,
file_type VARCHAR(50) NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (file_id)
REFERENCES file (file_id),
FOREIGN KEY (store_id)
REFERENCES storage (store_id)
);
怎么办?
答案 0 :(得分:0)
我找到了解决方案。实际上,我在外部这样添加了外键。因此,您需要先创建或迁移表,然后添加外键。
type存储结构{
ID int gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL;UNIQUE"
Store_Id字符串gorm:"type:varchar(190)";"NOT NULL";"UNIQUE"
}
type File struct {
ID int gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL;UNIQUE"
Organization_Id字符串gorm:"type:varchar(190)";"NOT NULL"
File_Id字符串gorm:"type:varchar(190)";"NOT NULL";"UNIQUE"
}
type File_Store_Linker struct {
ID int gorm: "type:int;primary_key;AUTO_INCREMENT;NOT NULL"
File_Id字符串gorm:"type:varchar(190)";"NOT NULL"
Store_Id字符串gorm:"type:varchar(190)";"NOT NULL"
File_Type字符串gorm:"type:varchar(50)";"NOT NULL"
}
func AddForeignKeys(gormDb * gorm.DB){ gormDb.Model(&File_Store_Linker {})。AddForeignKey(“ file_id”,“ file(file_id)”, “限制”,“限制”) gormDb.Model(&File_Store_Linker {})。AddForeignKey(“ store_id”,“ store(store_id)”,“ RESTRICT”,“ RESTRICT”) }