首頁  >  文章  >  後端開發  >  如何有效地將 GORM 查詢結果掃描到結構中:解決映射問題的指南

如何有效地將 GORM 查詢結果掃描到結構中:解決映射問題的指南

Barbara Streisand
Barbara Streisand原創
2024-10-27 05:25:29508瀏覽

How to Effectively Scan GORM Query Results into Structs: A Guide to Resolving Mapping Issues

將 GORM 查詢結果掃描到結構中

使用 GORM 查詢資料時,將結果掃描到自訂資料結構時可能會遇到問題。本文探討如何有效解決此類挑戰。

範例程式碼和問題描述

考慮以下程式碼,程式碼使用左聯接從兩個表(users 和credit_cards)擷取資料:

<code class="go">type res struct {
    id       int
    number   int
    user_id int
}

func getDataJoin() {
    new := []res{}
    db.Db.Table("users").Select("users.id as id, credit_cards.number as number, credit_cards.user_id as user_id").Joins("left join credit_cards on credit_cards.user_id = users.id").Scan(&new)
    fmt.Println("user\n", new)
}</code>

此查詢產生以下結果:

[
  {0 0 0},
  {0 0 0},
  {0 0 0},
  {0 0 0},
  {0 0 0},
  {0 0 0}
]

儘管在資料庫中獲得了正確的查詢結果集,但新數組僅由預設值組成。

解決方案:欄位命名約定與對應

要解決此問題,請確保 res 結構中的欄位名稱與資料庫列名稱對齊。預設情況下,GORM 希望欄位名稱與列名稱完全匹配。或者,您可以使用 gorm 標籤指定列和欄位之間的明確對應:

<code class="go">// Solution 1: Public Fields

type Res struct {
    ID       int
    Number   int
    UserID   int
}

// Solution 2: Explicit Mapping

type res struct {
    id       int      `gorm:"column:id"`
    number   int      `gorm:"column:number"`
    user_id  int      `gorm:"column:user_id"`
}</code>

透過套用這些解決方案,GORM 可以正確地將查詢結果掃描到新陣列中。

以上是如何有效地將 GORM 查詢結果掃描到結構中:解決映射問題的指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn