【问题标题】:How to define foreign key in GORM library model referencing to another table id?如何在引用另一个表 id 的 GORM 库模型中定义外键?
【发布时间】:2020-01-02 14:01:30
【问题描述】:

我有这三个模型

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)
);

怎么做?

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    我找到了解决方案。实际上我像这样在外部添加了外键。所以需要先创建或迁移表,再添加外键。

    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"`
    }
    
    func AddForeignKeys(gormDb *gorm.DB) {
         gormDb.Model(&File_Store_Linker{}).AddForeignKey("file_id","file(file_id)", 
        "RESTRICT","RESTRICT")
     gormDb.Model(&File_Store_Linker{}).AddForeignKey("store_id","store(store_id)"," 
         RESTRICT","RESTRICT")
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-13
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 2016-11-06
      • 1970-01-01
      • 2011-01-06
      • 2018-10-13
      相关资源
      最近更新 更多