登录
首页 >  Golang >  Go问答

在 Gorm 中如何同时使用预加载和筛选?

来源:stackoverflow

时间:2024-02-18 20:03:28 405浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《在 Gorm 中如何同时使用预加载和筛选?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

我的 go 代码中有以下嵌套结构:

type notification struct {
    serialnumber      string   `json:"serialnumber,omitempty"`
    ts                time.time `json:"ts,omitempty"`
    notificationkeys  []*notificationkeys   `json:"notificationkeys,omitempty" gorm:"foreignkey:notificationid"` 
    id                uint64                 `gorm:"primarykey;autoincrement:true" json:"-"`
}

type notificationkeys struct {
     key            string  `json:"key,omitempty"`
     value          string  `json:"value,omitempty"`
     id             uint64  `gorm:"primarykey;autoincrement:true" json:"-"`
}

我使用 gorm 来接收具有以下功能的通知:

type repo struct {
     db *gorm.db
}


func (r repo) getnotifications(serialnumber string, ts time.time) ([]*notification, error) {
     retval := []*notification{}
     if tx := tr.db.model(¬ification{}).preload(clause.associations).where("serial_number=? and ts <= ?", serialnumber, ts).order("ts desc").limit(3).find(&retval); tx.error != nil {
          return retval, tx.error
     }
     return retval, nil
}

到目前为止,这段代码正在运行:gorm 将我最近的三个通知及其键值对加载到我的 retval 数组中。

但是,由于存在错误,我的数据库中的通知是重复的,因此具有相同的时间戳。

sql server 和 gorm 都为此提供了 distinct 函数。我尝试在不同的地方更改我的功能,例如:

func (r repo) GetNotifications(serialNumber string, ts time.Time) ([]*Notification, error) {
     retval := []*Notification{}
     if tx := tr.db.Model(&Notification{}).Preload(clause.Associations).Where("serial_number=? AND ts <= ?", serialNumber, ts).Order("ts desc").Distinct("ts").Limit(3).Find(&retval); tx.Error != nil {
          return retval, tx.Error
     }
     return retval, nil
}

gorm 现在不会发送任何具有相同时间戳的通知,但是我的 notificationkeys 不再加载,数组为空。这两个函数是否不可组合,或者我是否遗漏了其他内容?


正确答案


我能够通过以下代码实现您的目标。首先,让我分享代码,然后我将引导您完成所有相关部分。

package main

import (
    "fmt"
    "time"

    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    "gorm.io/gorm/clause"
)

type notification struct {
    id               uint64              `gorm:"primarykey;autoincrement:true" json:"-"`
    serialnumber     string              `json:"craneserialnumber,omitempty"`
    ts               time.time           `json:"ts,omitempty"`
    notificationkeys []*notificationkeys `json:"notificationkeys,omitempty"`
}

type notificationkeys struct {
    id             uint64 `gorm:"primarykey;autoincrement:true" json:"-"`
    key            string `json:"key,omitempty"`
    value          string `json:"value,omitempty"`
    notificationid uint64
}

func main() {
    dsn := "host=localhost port=54322 user=postgres password=postgres dbname=postgres sslmode=disable"
    db, err := gorm.open(postgres.open(dsn))
    if err != nil {
        panic(err)
    }
    db.automigrate(¬ification{}, ¬ificationkeys{})

    // seed some dummy data
    db.create(¬ification{id: 1, serialnumber: "001", ts: time.date(2023, 7, 1, 10, 30, 0, 0, time.utc)})
    db.create(¬ification{id: 2, serialnumber: "001", ts: time.date(2023, 7, 1, 10, 30, 0, 0, time.utc)})
    db.create(¬ification{id: 3, serialnumber: "003", ts: time.date(2023, 7, 1, 10, 35, 0, 0, time.utc)})
    db.create(¬ificationkeys{key: "a", value: "1", notificationid: 1})
    db.create(¬ificationkeys{key: "b", value: "1", notificationid: 2})
    db.create(¬ificationkeys{key: "c", value: "1", notificationid: 3})

    // get logic
    var notifications []notification
    err = db.debug().
        model(¬ification{}).
        preload(clause.associations).
        where("id in (?)", db.debug().model(¬ification{}).group("serial_number,ts").select("min(id) as id").limit(2)). // subquery
        order("ts desc").
        find(¬ifications).error
    if err != nil {
        panic(err)
    }

    for _, v := range notifications {
        fmt.println(v)
        for _, vv := range v.notificationkeys {
            fmt.println(*vv)
        }
    }
}

代码主要分为三部分。

结构体定义

我必须通过添加以下字段来调整 notificationkeys 结构的定义:

NotificationId uint64

剩下的代码应该没问题。

引导逻辑

你可以忽略它。我通过 docker 运行 postgres 容器。然后,我创建了一个 gorm db 客户端进行交互。另外,我向数据库添加了一些虚拟数据以便能够重现该问题。

获取逻辑

我能够使用以下方法解决该问题(仅提到最相关的方法):

  • 预加载:加载关系 notifications
  • 子查询:内联编写,但您可以从 where 推断它。这通过 serial_numbertsnotifications 表的记录进行分组,从而过滤掉重复的记录

由于这个查询可以分成两个较小的查询,您应该能够实现您的目标。
添加最终代码只是为了循环我们得到的结果。
如果一切正常或者您需要其他东西,请告诉我,谢谢!

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>