本文介绍了如何根据父列有条件地预加载子级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用以下语法预加载与 Order
相关的所有 Guests
:
I'm able to preload all Guests
related to Order
using this syntax:
Table(order).
Preload("Guests").
Where("order.code = ?", orderCode).
First(&order).
Error
是否可以根据 Order
表中一列的条件来预加载 Guests
?这是我要实现的SQL:
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)
注意:
我知道这种预加载语法(这不会从订单表列中获取价值,仅当我自己提供价值时才有效):
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)
推荐答案
您可以在Gorm中使用自定义预加载SQL
You can use Custom Preloading SQL in Gorm
示例:按名称desc预加载来宾订单.
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;
要处理父子条件,可以使用 JOIN
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)
这篇关于如何根据父列有条件地预加载子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!