我可以使用以下语法预加载与Guests
相关的所有Order
:
Table(order).
Preload("Guests").
Where("order.code = ?", orderCode).
First(&order).
Error
是否可以根据
Guests
表中某一列的条件来预加载Order
?这是我想要实现的SQL: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)
注意:
我知道这种Preload语法(这不会从订单表列中获取价值,仅当我自己提供价值时才有效):
Preload("Guests", "some_column_in_guest_tbl = ?", some_column_in_order_tbl)
最佳答案
您可以在Gorm中使用Custom Preloading SQL
示例:按名称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;
要处理父子条件,可以使用
JOIN
db.Joins("JOIN orders ON orders.id = guests.order_id ").Find(&guests)
两者结合可能有效。喜欢
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)