Search code examples
goforeign-keysgo-gorm

GORM: Define multiple columns with same foreign key


I am creating a Golang MySQL project where I am using GORM. I have a table called accounts with fields

    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 called 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 cant figure out how to define this in go gorm? Can I have two fields with with foreign key to same column of another table? How to do this?


Solution

  • Did it using this. 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"`
    }