首頁  >  文章  >  後端開發  >  在 Gorm 中實現與值數組的關係

在 Gorm 中實現與值數組的關係

WBOY
WBOY轉載
2024-02-09 08:48:09628瀏覽

在 Gorm 中实现与值数组的关系

在 Gorm 中,實作與值陣列的關係是一項非常有用的功能。 Gorm 是一個流行的 Go 語言 ORM(物件關聯映射)庫,它允許開發者使用 Go 語言來操作資料庫。與傳統的關係型資料庫不同,值數組是一種特殊的資料結構,它允許將多個值作為一個整體儲存在資料庫中的某個欄位中。這對於儲存一些複雜的資料結構或提高查詢效率都非常有幫助。在本文中,我將向大家介紹如何在 Gorm 中實現與值數組的關係,以及如何使用它來提升開發效率。

問題內容

我正在嘗試使用 go 和 gorm 實作發票應用程式的模型。我已經定義了發票結構,並希望包含來自單獨結構的發票行項目。

type invoice struct {
    base
    companyid  string `gorm:"not null"`
    company    company
    invoiceno  string     `gorm:"not null"`
    currency   string     `gorm:"not null;default:'gbp'"`
    total      float64    `gorm:"not null"`
    terms      int        `gorm:"not null;default:30"`
    issueddate time.time  `gorm:"not null"`
    duedate    time.time  `gorm:"not null"`
    paid       bool       `gorm:"not null"`
    lineitems  []lineitem `gorm:"foreignkey:invoiceid"`
    void       bool       `gorm:"default:false"`
}

這是我的 lineitem 結構。

type lineitem struct {
    base
    service     string `gorm:"not null"`
    description string `gorm:"not null;"`
    amount      float64
    count       int
    unitbase    string  `gorm:"not null;default:'days'"` // days or hours
    total       float64 `gorm:"not null"`
}

當我嘗試建立應用程式時,出現以下錯誤。

... got error invalid field found for struct github.com/repo/API/database/models.Invoice's field LineItems: define a valid foreign key for relations or implement the Valuer/Scanner interface

我的想法是,我可以定義一個有限的設定訂單項,可以從固定費率和說明中進行選擇,以限制重複。

我不確定我的處理方式是否正確。

所以我的問題是,是否可以透過這種方式包含關係模型中的項目陣列?

解決方法

根據您的列名稱,我可以想到三種方法來實現此目的:

  1. 使用預設語法(無 gorm:foreignkey

    type invoice struct {
         id     //this is the primary key, may also be in your base model
         lineitems []lineitem
         ..other fields
     }
    
     type lineitem struct {
         id          //primary key of lineitem
         invoiceid   //automatically this will be your foreign key
         ..other fields
     }
  2. 指定自訂外鍵(假設第二個結構具有不同的列名稱,您希望將其作為外鍵)

    type invoice struct {
         id     //this is the primary key, may also be in your base model
         lineitems []lineitem `gorm:"foreignkey:parentid"`
         ..other fields
     }
    
     type lineitem struct {
         id          //primary key of lineitem
         parentid   //this is the custom column referencing invoice.id
         ..other fields
     }
  3. 或兩個結構體有不同的欄位名稱

    type Invoice struct {
         ID     //this is the primary key, may also be in your base model
         InvoiceNum 
         Lineitems []LineItem `gorm:"foreignKey:ParentNum;references:InvoiceNum"`
         ..other fields
     }
    
     type LineItem struct {
         ID          //primary key of LineItem
         ParentNum   //this is now referencing Invoice.InvoiceNum
         ..other fields
     }

以上是在 Gorm 中實現與值數組的關係的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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