簡體   English   中英

具有相同外鍵和引用主鍵名稱的 Gorm 所屬關系

[英]Gorm belongs-to relation with same foreignKey and referenced primary key name

當我無法使用自動表創建時,Gorm 有一個奇怪的錯誤。 如果我使用與其他表中引用的外鍵相同的主鍵字段名稱,則無法正確處理。

工作示例 - User.ComIDCompany.ID的引用:

type User struct {
    gorm.Model
    ComID string
    Company Company `gorm:"foreignKey:ComID;references:ID"`
}
type Company struct {
    ID   string `gorm:"primaryKey"`
}

產生以下自動遷移序列:

CREATE TABLE "companies" ("id" text,"name" text,PRIMARY KEY ("id"))
CREATE TABLE "users" ("id" bigserial,"created_at" timestamptz,"updated_at" timestamptz,"deleted_at" timestamptz,"name" text,"com_id" text,PRIMARY KEY ("id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "companies"("id"))

但是如果我將第二個表的 ID 更改為ComID

type User struct {
    ComID string
    Company Company `gorm:"foreignKey:ComID;references:ComID"`
}
type Company struct {
    ComID   string `gorm:"primaryKey"`
}

一切都停止工作。 gorm 嘗試執行不正確的 sql 代碼,此時表 users 不存在。

CREATE TABLE "companies" ("com_id" text,"name" text,PRIMARY KEY ("com_id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "users"("com_id"))

有什么想法可以為 gorm 提供正確的描述(創建不同的列名除外)?

如果重要的話,在這種情況下,sql 的方言是 Postgres。

gorm 不允許:

引用包括 self 字段

您可以更改代碼:relationship.go line 559

            if ref.OwnPrimaryKey {
                constraint.Schema = ref.ForeignKey.Schema
                constraint.ReferenceSchema = rel.Schema
            } else {
                constraint.Schema = rel.Schema
                constraint.ReferenceSchema = ref.PrimaryKey.Schema
            }

            if false {
                constraint.Schema = ref.ForeignKey.Schema
                constraint.ReferenceSchema = rel.Schema
            } else {
                constraint.Schema = rel.Schema
                constraint.ReferenceSchema = ref.PrimaryKey.Schema
            }

如果你跑

db.Debug().AutoMigrate(User{})

你會看到它:

CREATE TABLE "companies" ("com_id" text,"name" text,PRIMARY KEY ("com_id"),CONSTRAINT "fk_users_company" FOREIGN KEY ("com_id") REFERENCES "users"("com_id"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM