Use "parent" table id in gorm custom preloading when you don't know it yet

14 Views Asked by At

I have a struct and I want to find all entries and preload the child entries too. The issue is that the logic to load those child entries is a bit complex, and I am only able to load it using a RAW query, the raw query looks something like this:

(select T.*
from my_table t
inner join (
    select software_name, max(edate) as MaxDate
    from my_table WHERE edate < '2024-03-01'
    group by software_name
) tm on t.software_name = tm.software_name and t.edate = tm.MaxDate
WHERE edate < '2024-03-01' AND user_id = 1
UNION 
SELECT T.* FROM my_table T WHERE edate BETWEEN '2024-03-01' AND '2024-04-01' AND user_id = 1) ORDER BY edate

When using gorm if I use a normal preload (so something like .Preload(User.MyTables)), it works, and filter the entries for that user, but when using a RAW sql, I can't add that user id filter, because I don't know the user id beforehand (since I am doing a get all).

I tried something like this (debugging I saw that the user id is something like ~~~~~ct~~~~.user_id)

func applicableInputs(timePeriod common.TimePeriod) func(db *gorm.DB) *gorm.DB {
    return func(db *gorm.DB) *gorm.DB {
        return db.Raw("(SELECT T.*\nFROM my_table t\nINNER JOIN (\n    SELECT software_name, max(modify_time) as MaxDate\n FROM my_table WHERE modify_time < @start_time AND user_id = @user_id\n    GROUP BY software_name\n) tm ON t.software_name = tm.software_name AND t.modify_time = tm.MaxDate\nWHERE modify_time < @start_time \nUNION \nSELECT T.* FROM my_table T WHERE modify_time BETWEEN @start_time AND @end_time AND user_id = @user_id) ORDER BY modify_time", map[string]any{"start_time": timePeriod.StartTime, "end_time": timePeriod.EndTime, "user_id": "~~~ct~~~.user_id"})
    }
}

But it does not work. So my question is, is there any way to use the parent id in a raw sql for preloading?

0

There are 0 best solutions below