How to preload child conditionally based on parent column?

时间秒杀一切 提交于 2021-01-29 13:28:45

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!