Home > Enterprise >  One-to-many association get data from the one table
One-to-many association get data from the one table

Time:03-22

I'm new to Golang and Gorm, and I couldn't find the anwswer. In a rest api, I want my json to come with values from the one table relation.

type Product struct {
    gorm.Model   
    Name             string       
    Description      string       
    Weight           string
    TypeID           uint
}
type Type struct {
    ID                   string         `gorm:"primaryKey;"`
    Name                 string
    Product              []Product

}

and I want my Product json to come with the ID and Name from Type. but this doesn't work.

var product Product
id:=1
db.Preload("Type").First(&product, id)

Do I have to do something like this in the struct?

type Product struct {
    gorm.Model   
    Name             string       
    Description      string       
    Weight           string
    Type             Type 
}

CodePudding user response:

If you want to load Type.ID and Type.Name into Product.ID and Product.Name, you need to specifically select fields from two tables:

var product Product
id:=1
db.Joins("JOIN types ON types.id = products.type_id"). Select("types.id, types.name, products.description, products.weight, products.type_id").First(&product, id)

If you want to separate Type fields into a separate field in the Product struct, you need to make the following changes:

type Product struct {
    gorm.Model   
    Name             string       
    Description      string       
    Weight           string
    TypeID           uint
    Type             Type 
}

var product Product
id:=1
db.Preload("Type").First(&product, id)

Here, all of the Type fields will be loaded into the Product.Type field.

  • Related