I'm newbie in Go and GORM. I'm having a problem with gorm when I want to join two table and select all field in two table.
My model:
Action:
type Action struct {
ID uint64
Type int
Url string
}
type Reminder struct {
ID uint64 `gorm:"primary_key"`
MerchantID uint64
MerReminderID string
Title string
Description string
ActionID uint64
Action *Action `gorm:"save_associations:false"`
Payload string
StartAt time.Time `gorm:"-"`
EndAt time.Time `gorm:"-"`
}
type UserReminder struct {
UserID uint64
ReminderID uint64
Reminder Reminder
StartAt time.Time
EndAt time.Time
Expired bool
}
My request: I want to get all Reminder
of once UserID
.
- Solution 1:
var reminders []*models.Reminder
err := db.Set("gorm:auto_preload", true).
Raw("SELECT * FROM user_reminders AS ur, reminders AS r WHERE ur.reminder_id = r.id AND ur.user_id = ?", userID).
Preload("Actions").
Scan(&reminders)
=> Promblem: Select all column when join two table but Object Action
can't preloading.
- Solution 2:
var reminders []*models.Reminder
err := db.Set("gorm:auto_preload", true).
Joins("JOIN user_reminders ON user_reminders.reminder_id = reminders.id").
Where("user_reminders.user_id = ? AND user_reminders.end_at >= ? AND user_reminders.deleted_at IS NULL", userID, time.Now()).
Find(&reminders)
=> Problem: Auto-preload success object Action
and select all column in table Reminder
. But miss two column Start_At
and End_At
in table User_Reminder
Please help me this problem. In my case, I want to auto preloading object Action and select all column when join two table Reminder
and User_Reminder
Thanks so much.