Golang gorm query with joins into struct with structs

I need to be able to do a query with joins and fill a struct with data, is that possible?

For example this query:

err := db.Select("orders.*, user.customer_id, user.first_name, user.last_name, user.email").Where("orders.created_at >= now() - interval 3 day").Joins("left join users as user on user.customer_id = orders.customer_id").Find(&orders).Error

The reason I want to build the query this way, is because there are a lot of variables (i.e. filters) so the query may differ a lot but the data is always the same. Its just the conditions that change in the query i.e. color, material, gender and that kind of stuff.

This will return the correct data, but what I actually want is to be able to fill a struct like this:

type Orders struct {
	CustomerId    int       `json:"customerId"`
	User          Users     `json:"user"`
    Products      []Products`json:"products"`
	Method        string    `json:"method"`
	Amount        float64   `json:"amount"`
	Subtotal      float64   `json:"subtotal"`
	Total         float64   `json:"total"`
	Btw           float64   `json:"btw"`
	Status        string    `json:"status"`
	OrderMailSend int       `json:"orderMailSend"`
}

In which the “user” obviously will contain a struct with user data, and the “products” will contain a slide of product structs.

I am unable to get this working in a efficiënt way. I hope someone call tell me how to do it or steer me in the correct direction.

The table name with users is “users” and the id to match is called “customer_id”.

The orders table is called “orders” and has a column “customer_id” as well which we can use to match.

My Go structs:

type Orders struct {
	CustomerId    int     `json:"customerId"`
	Users         Users   `json:"users"`
	Method        string  `json:"method"`
	Amount        float64 `json:"amount"`
	Subtotal      float64 `json:"subtotal"`
	Total         float64 `json:"total"`
	Btw           float64 `json:"btw"`
	Status        string  `json:"status"`
	OrderMailSend int     `json:"orderMailSend"`
}

type Users struct {
	CustomerId int    `json:"customerId"`
	Email      string `json:"email"`
	FirstName  string `json:"firstName"`
	LastName   string `json:"lastName"`
}

The erorr I am receiving is:

can’t preload field users for app.Orders

And in the case where I got a query with joins working, my struct would only fill the order details and leave the “customer” details nil.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.