未创建GO GORM外键约束

izkcnapc  于 2023-06-27  发布在  Go
关注(0)|答案(3)|浏览(107)

我在为Belongs to关系创建外键约束时遇到问题。
包含外键的结构:

type Summary struct {
    Id          string  `gorm:"primaryKey"`
    OwnerId     *string `gorm:"foreignKey:OwnerId references:Id;not null"`
    Title       string
}

摘要所属的结构:

type Owner struct {
    Id        string `gorm:"primaryKey"`
    Name      string
}

它在SQL中创建表没有问题,但SQL模式在owner_id列的汇总表中不包含外键约束,因此当所有者不存在时可以插入Summary。

xdnvmnnf

xdnvmnnf1#

在我看来,最终成功但不是完美的解决方案是在Summary中引用Owner结构体,如下所示:

type Summary struct {
    Id          string  `gorm:"primaryKey"`
    OwnerId     string 
    Owner       Owner   `gorm:"foreignKey:OwnerId"`
    Title       string
}

我想知道这是不是唯一的办法

cgfeq70w

cgfeq70w2#

你用的是什么版本的gorm?如果您使用的是库的v1,请尝试切换到v2。我在使用库的v1时遇到了类似的问题。
v1依赖下载

go get -u github.com/jinzhu/gorm

v2依赖下载

go get -u gorm.io/gorm
oewdyzsn

oewdyzsn3#

在我们的例子中,我们需要在列名/字段名方面具有完全的灵活性,因为我们正在迁移一个最初由SQLAlchemy创建的现有数据库。不使用Gorm期望的名称会导致不生成外键。
使用Gorm 2.0,由于某种原因仍然有v1标签(gorm.io/gorm v1.25.1),技巧是正确使用foreignkey(必须指向本地字段)和references(大多数指向外部表中的远程字段)注解完全任意的名称:

type Other struct {
    OtherId int32 `gorm:"primarykey; column:custom_col_other_id"`
}

type Main struct {
    MainId    int32 `gorm:"primarykey; column:custom_col_main_id"`
    FkOtherId int32 `gorm:"column:custom_col_fk_other_id"`
    OtherRef  Other `gorm:"foreignkey:FkOtherId;references:OtherId"`
}

...

dbClient.AutoMigrate(&Other{})
dbClient.AutoMigrate(&Main{})

这将产生正确的外键关系:

Table "public.others"
       Column        |  Type   | Collation | Nullable |                       Default                       
---------------------+---------+-----------+----------+-----------------------------------------------------
 custom_col_other_id | integer |           | not null | nextval('others_custom_col_other_id_seq'::regclass)
Indexes:
    "others_pkey" PRIMARY KEY, btree (custom_col_other_id)
Referenced by:
    TABLE "mains" CONSTRAINT "fk_mains_other_ref" FOREIGN KEY (custom_col_fk_other_id) REFERENCES others(custom_col_other_id)"

                                            Table "public.mains"
         Column         |  Type   | Collation | Nullable |                      Default                      
------------------------+---------+-----------+----------+---------------------------------------------------
 custom_col_main_id     | integer |           | not null | nextval('mains_custom_col_main_id_seq'::regclass)
 custom_col_fk_other_id | integer |           |          | 
Indexes:
    "mains_pkey" PRIMARY KEY, btree (custom_col_main_id)
Foreign-key constraints:
    "fk_mains_other_ref" FOREIGN KEY (custom_col_fk_other_id) REFERENCES others(custom_col_other_id)

相关问题