简体   繁体   English

使用 GORM 在同一个表上设置两个外键时,MS-SQL 服务器抛出错误

[英]MS-SQL server throws error when two foreign keys are set on same table using GORM

I am doing database migrations using GORM.我正在使用 GORM 进行数据库迁移。 So I define structs and run them through GORM's AutoMigrate function.所以我定义结构体并通过 GORM 的 AutoMigrate 函数运行它们。

    type Person struct {
        ID          string    `gorm:"type:varchar(36);primary_key"`
    }

    err := db.Table("persons").AutoMigrate(&Person{}).Error

    type Address struct {
        ID         string      `gorm:"type:varchar(36);primary_key"`
        PersonID   string      `gorm:"column:person_id;type:varchar(36);NOT NULL"`
    }

    err = db.AutoMigrate(&Address{}).Error

    err = db.Model(&Address{}).AddForeignKey("person_id", "persons(id)", "NO ACTION", "CASCADE").Error

    type Contact struct {
        ID            string      `gorm:"type:varchar(36);primary_key"`
        AddressID     null.String `gorm:"column:address_id;type:varchar(36);NOT NULL"`
        PersonID      string      `gorm:"column:person_id;type:varchar(36);NOT NULL"`
    }

    err = db.AutoMigrate(&Contact{}).Error

    err = db.Model(&Contact{}).AddForeignKey("address_id", "addresses(id)", "NO ACTION", "CASCADE").Error

    err = db.Model(&Contact{}).AddForeignKey("person_id", "persons(id)", "NO ACTION", "CASCADE").Error

In the above code, which ever is the second call to the AddForeignKey function on Contacts table is giving error :在上面的代码中,第二次调用 Contacts 表上的 AddForeignKey 函数时出现错误:

mssql: Could not create constraint or index. See previous errors.

Even if I move person_id foreign key above address_id foreign key, then address_id foreign key fails.即使我将 person_id 外键移到 address_id 外键上方,address_id 外键也会失败。

I am running MS-SQL server using latest docker container setup(microsoft/mssql-server-linux:latest).我正在使用最新的 docker 容器设置(microsoft/mssql-server-linux:latest)运行 MS-SQL 服务器。 Is this something regarding naming of constraint.这是关于约束命名的事情吗? If yes, then how can we set using GORM?如果是,那么我们如何使用GORM进行设置? Everything works fine with My-SQL. My-SQL 一切正常。

It would be really helpful if I get a solution.如果我得到解决方案,那将非常有帮助。 I cannot run raw queries.我无法运行原始查询。 Migrations have to be done using GORM only.迁移必须仅使用 GORM 完成。

Thank You谢谢你

Multiple foreignkeys can't have 'no action', 'cascade' on the same table.多个外键不能在同一个表上有“无操作”、“级联”。 If u use no action, no action u can but u have to handle deletion and updating your self.如果你不使用任何动作,你可以没有任何动作,但你必须处理删除和更新你的自我。 What I usually do is turn on logmode and copy paste the log sql statement into SQL.我通常做的是打开logmode并将log sql语句复制粘贴到SQL中。 This will give ua more clear error.这将给出更清晰的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM