Trupti Katkar
Trupti Katkar

Reputation: 3

required constraints to have foreign key which references to unique key in has-many relationship in gorm

How to have foreign key which references to unique key and not to primary key in gorm? I have below to data structures having has many relationship. with below constraints I am able to add ModuleData in db but I am not able to add the DimensionOrderData. However If I have foreign key which references to primary key then that works. Do I need to add any more constraint to make it work?

typeDimensionOrderDatastruct {​​​​​​​​
    ModuleID       int64`gorm:"primary_key;column:module_internal_id"`
    DimensionID    int64`gorm:"primary_key;column:dimension_id"`
    SequenceNumber int`gorm:"column:sequencenumber_cnt"`
}​​​​​​​​


// ModuleData : Module data

typeModuleDatastruct {​​​​​​​​
    ID             string`gorm:"primary_key;type:uuid;column:module_id"`
    InternalID     int64`gorm:"unique;column:internal_id"`
    Name           *string`gorm:"column:name_nm"`
    Reference      *string`gorm:"column:reference_txt"`
    DimensionOrder []DimensionOrderData `gorm:"foreignkey;column:module_internal_id;references:internal_id"`
}​​​​​​​​

Upvotes: 0

Views: 742

Answers (1)

Maneesh Babu M
Maneesh Babu M

Reputation: 155

Gorm documentation here https://gorm.io/docs/has_many.html, specifies that you can override foreign key as follows

type User struct {
  gorm.Model
  CreditCards []CreditCard `gorm:"foreignKey:UserRefer"`
}

type CreditCard struct {
  gorm.Model
  Number    string
  UserRefer uint
}

Upvotes: 1

Related Questions