首頁  >  文章  >  後端開發  >  GORM:使用相同的外鍵定義多個列

GORM:使用相同的外鍵定義多個列

WBOY
WBOY轉載
2024-02-13 11:45:161041瀏覽

GORM:使用相同的外鍵定義多個列

php小編草今天為大家帶來一個有關GORM的問題:如何在GORM中使用相同的外鍵定義多個欄位?在資料庫設計中,有時我們需要在多個表中使用相同的外鍵列,這就需要我們在GORM中進行適當的定義和配置。接下來,我們將詳細介紹如何在GORM中實現這項需求,以及相關的注意事項。讓我們一起來探索這個有趣的主題吧!

問題內容

我正在建立一個使用 GORM 的 Golang MySQL 專案。我有一個名為accounts 的表,其中包含欄位

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"`

現在我想製作一個名為帶有欄位的交易的表格

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

我不知道如何在 go Gorm 中定義它?我可以有兩個帶有外鍵的字段到另一個表的同一列嗎?如何做到這一點?

解決方法

是用這個做的嗎?謝謝!

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"`
}

以上是GORM:使用相同的外鍵定義多個列的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除