dongshadu4498 2019-04-24 03:26
浏览 285

Go-Gorm | 如何使用扫描和预加载

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.

  • 写回答

1条回答 默认 最新

  • dongshun7312 2019-04-24 08:19
    关注

    @Anh Vinh Huynh Gorm Scan method doesn't support Preloading, so you must use the Find method instead. (your Soloution2) And remove gorm:"-" tag from StartAt and EndAt of

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源