问题
I'm able to preload all Guests
related to Order
using this syntax:
Table(order).
Preload("Guests").
Where("order.code = ?", orderCode).
First(&order).
Error
Is it possible to to preload Guests
based on a condition on a column in Order
table? here is SQL for what I want to achieve:
SELECT * FROM orders WHERE code = "xyz"
SELECT * FROM guests WHERE (order_id IN (1)) AND (some_column_in_guest_tbl = some_column_in_order_tbl)
Note:
I'm aware of this Preload syntax (this doesn't take value from order table column, it only works if I provide value myself):
Preload("Guests", "some_column_in_guest_tbl = ?", some_column_in_order_tbl)
回答1:
You can use Custom Preloading SQL in Gorm
Example: Preload guests order by name desc.
db.Where("code = ?", orderCode).Preload("Guests", func(db *gorm.DB) *gorm.DB {
return db.Order("guests.name DESC")
}).Find(&orders)
//// SELECT * FROM orders WHERE orders.code = "ABC";
//// SELECT * FROM guests WHERE order_id IN (1,2,3,4) order by guests.name DESC;
For working with parent-child condition you can use JOIN
db.Joins("JOIN orders ON orders.id = guests.order_id ").Find(&guests)
Combining both may work. Like
db.Where("code = ?", orderCode).Preload("Guests", func(db *gorm.DB) *gorm.DB {
return db.Joins("JOIN orders ON orders.some_column_in_order_tbl = guests.some_column_in_guest_tbl")
}).Find(&orders)
来源:https://stackoverflow.com/questions/60908615/how-to-preload-child-conditionally-based-on-parent-column