使用Gorm将值从一列映射到单独表中的另一列

Given the following one-to-many relationship (One Receipt has many LineItem's), I would like to map the Price field from the Receipt table into the Price field of LineItem table (for each LineItem in Product).

Receipt Schema

type Product struct {
ID             uint       `json:"id"`
TotalPrice     float64    `json:"total"`
LineItems      []LineItem `json:"lineItems"`

}

LineItem Schema

type LineItem struct {
    ID          uint    `json:"id"`
    ProductID   uint    `json:"productID"`
    Price       float64 `json:"price"`
}

I'm currently using gorm, an ORM for Go, but I can't find the functionality to support what I'm looking for.

Assuming that you have 3 tables/models, Receipt, Product, and LineItem, you can add field that reference Product in LineItem model like so :

type Receipt struct {
    ID             uint       `json:"id"`
    TotalPrice     float64    `json:"total"`
    LineItems      []LineItem `json:"lineItems"`
}

type Product struct {
    ID          uint    `json:"id"`
    Price       float64 `json:"price"`
}

type LineItem struct {
    ID          uint     `json:"id"`
    ProductID   uint     `json:"productID"`
    Product     *Product `json:"product"`
}

Then you can query Receipt while populating LineItems field as well as Product field in each LineItem by using gorm's Preload feature:

db.Preload("LineItems").Preload("LineItems.Product").Find(&receipt)

This way you will have the price info in each LineItem accessible through Product field:

for _, li in receipt.LineItems {
    fmt.Println(li.Product.Price)
}