I have this data design: A Transaction belongs to a Mandate, which in turn belongs to a Client. Or expressed with structs:
type Transaction struct {
shared.Transaction // transaction data
MandateID string
Mandate *Mandate
}
type Mandate struct {
shared.Mandate // mandate data
ClientID string
Client *Client
Transactions []Transaction
}
type Client struct {
shared.Client // client data
Mandates []Mandate
}
I've been trying to preload transactions along with their mandate and client data using joins preloading. Where it is noted that this preloading only works for "has-one" or "belongs-to" type relationships.
This works nicely if I just want the Transaction and Mandate data:
var trx []rdb.Transaction
err = t.db.
Joins("Mandate").
Find(&trx, "batch_id = ?", batchID).Error
However as soon as I try to also load the clients, then gorm generates invalid SQL. Code:
var trx []rdb.Transaction
err = t.db.
Joins("Mandate").
Joins("Mandate.Client").
Find(&trx, "batch_id = ?", batchID).Error
I used to use normal preloading before, but the multiple queries that Preload kicks off started to become a serious performance concern. Writing the entire query in SQL and scanning the result is also an option, but that defeats the purpose of using an ORM in the first place.
How can I use gorm to fetch the transactions with their mandate and client data in a single query?