简体   繁体   中英

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

I am doing database migrations using GORM. So I define structs and run them through GORM's AutoMigrate function.

    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 :

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.

I am running MS-SQL server using latest docker container setup(microsoft/mssql-server-linux:latest). Is this something regarding naming of constraint. If yes, then how can we set using GORM? Everything works fine with 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.

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. This will give ua more clear error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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