我正在開發一個Gorm用于數據庫操作的 Golang 項目。當我在兩個表上執行Join()運算符時,這兩個表有兩個同名的列 ( id),它運行時沒有任何錯誤或警告,但在使用 解析步驟時出現問題Find(),它顯示struct1.id為struct2.id.在下面的代碼中,我試圖通過在某些條件下連接兩個表來填充兩個結構的兩個數組。var array1 []Struct1var array2 []Struct2queryRes := gormClient.Model(&Struct1{}).Select("*"). Joins("Join table 2 on some conditions"). Where("Other conditions"). Find(&array1).Find(&array2)我知道重命名模型的列名或結構標簽會有所幫助。但我想知道是否有任何其他解決方案比修改數據庫結構更方便。謝謝你,感謝你的幫助。
1 回答

慕勒3428872
TA貢獻1848條經驗 獲得超6個贊
此問題已在此線程中提出。貢獻者通過創建一個包含兩個嵌入式結構的新結構解決了這個問題,如下所示:
type Struct1And2 struct {
Struct1 Struct1 `gorm:"embedded"`
Struct2 Struct2 `gorm:"embedded"`
}
然后執行查詢。
var struct1and2 []Struct1And2
var array1 []Struct1
var array2 []Struct2
gormClient.Model(&Struct1{}).Select("*").
Joins("Join table 2 on some conditions").
Where("Other conditions").
Find(&struct1and2)
// Now we need one more step to build array1 and array2 from struct1and2 separately.
無論如何,我還是希望Gorm將來支持一個一個地掃描結構(就像我在問題中所做的那樣),看起來很方便。
- 1 回答
- 0 關注
- 157 瀏覽
添加回答
舉報
0/150
提交
取消