我想要加入和预加载两个表,并将结果合并,但是我无法得到期望的结果。
我尝试过使用"gorm:foreigKey=ProductID;references=ID;embedded;embeddedPrefix:product",并尝试了不同的组合,但仍然无法将product.name和product.description的数据合并到TransactionItem中。如果我将Transaction Item更改为以下内容:
我可以通过循环这个结果并手动设置名称和描述来实现所需的结果,但我认为 GORM 应该有一种自动完成这个任务的方式,对吗?提前谢谢你。
models.go
type Product struct {
ID uint `json:"-"`
Name string `json:"name"`
Description string `json:"description"`
}
type TransactionItem struct {
ID uint `json:"-"`
ProductID uint `json:"-"`
Qty int `json:"qty"`
Price int `json:"price"`
Product // I want to combine properties of Product into Transaction Item
}
controllers.go
var items []TransactionItem
if e := db.Preload("Product").Find(&items).Error; e != nil {
log.Println(e)
}
期望结果:
[
{
"qty": 1,
"price": 50,
"name": "Product name",
"description": "This is the product description"
}, { ... }
]
我尝试过使用"gorm:foreigKey=ProductID;references=ID;embedded;embeddedPrefix:product",并尝试了不同的组合,但仍然无法将product.name和product.description的数据合并到TransactionItem中。如果我将Transaction Item更改为以下内容:
type TransactionItem struct {
ID uint `json:"-"`
ProductID uint `json:"-"`
Qty int `json:"qty"`
Price int `json:"price"`
Product Product
}
//This will work and display data from product table, but the result is as follow:
[
{
"qty": 1,
"price": 50,
"product": {
"name": "Product name",
"description": "This is the product description"
}
}, { ... }
]
我可以通过循环这个结果并手动设置名称和描述来实现所需的结果,但我认为 GORM 应该有一种自动完成这个任务的方式,对吗?提前谢谢你。