php editor Baicao brings you a question about GORM today: How to use the same foreign key to define multiple columns in GORM? In database design, sometimes we need to use the same foreign key column in multiple tables, which requires us to make appropriate definitions and configurations in GORM. Next, we will introduce in detail how to implement this requirement in GORM, as well as related considerations. Let’s explore this interesting topic together!
I am creating a Golang MySQL project using GORM. I have a table called accounts which contains field
ID uint `json:"id" gorm:"primary_key;auto_increment;not_null"` Name string `json:"name"` Company string `json:"company"` GSTIN string `json:"gstin"` AccountNo string `json:"accountNo" gorm:"unique"` IFSC string `json:"ifsc"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"`
Now I want to make a table named Transactions with fields
ID uint `json:"id" gorm:"primary_key;auto_increment;not_null"` Amount float64 `json:"amount"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` Date time.Time `json:"Date"` PaymentMode string `json:"paymentMode"` SourceId uint `json:"source"` ------>>>>> Want this to be AccountID foreign key UTR string `json:"utr" gorm:"uniqueIndex"` DestinationId uint `json:"to"` ------>>>>> Want this to be AccountID foreign key Account Account
I don't know how to define it in go Gorm? Can I have two fields with foreign keys to the same column of another table? How do i do this?
Is this done? Thanks!
type Debit struct { ID uint `json:"id" gorm:"primary_key;auto_increment;not_null"` Amount float64 `json:"amount"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` PaymentMode string `json:"paymentMode"` SourceId uint `json:"sourceId"` UTR string `json:"utr" gorm:"uniqueIndex"` DestinationId uint `json:"destinationId"` SourceAccount Account `gorm:"foreignKey:SourceId"` DestinationAccount Account `gorm:"foreignKey:DestinationId"` }
The above is the detailed content of GORM: Define multiple columns with the same foreign key. For more information, please follow other related articles on the PHP Chinese website!