为了账号安全,请及时绑定邮箱和手机立即绑定

Golang GORM 搜索条件

Golang GORM 搜索条件

Go
繁花不似锦 2023-05-15 15:06:22
使用 gorm 和 postgres 在 Golang 中编写网络服务器时,我一直误解了以下代码中第二次循环迭代中到底发生了什么:...for _, t := range tasks {    newDbConn := db.SchoolServerDB.Debug().New()    err = newDbConn.Where("id = ?", t.DayID).First(&day).Error    if err != nil {        return errors.Wrapf(err, "Error query day with id='%v'", t.DayID)    }    ...}...第一次迭代调试:SELECT * FROM "days"  WHERE "days"."deleted_at" IS NULL AND ((id = '8')) ORDER BY "days"."id" ASC LIMIT 1第二次迭代调试:SELECT * FROM "days"  WHERE "days"."deleted_at" IS NULL AND "days"."id" = '8' AND ((id = '38')) ORDER BY "days"."id" ASC LIMIT 1关键问题是:尽管每次迭代都会创建一个新连接,但为什么搜索条件会累积?根据文档,每次都必须清除搜索条件。我想得到这样的第二个结果:SELECT * FROM "days"  WHERE "days"."deleted_at" IS NULL AND ((id = '38')) ORDER BY "days"."id" ASC LIMIT 1任何帮助表示赞赏!UPD:db.SchoolServerDb 只是 *gorm.DB 而 Debug() 是它的方法表 'days' 由结构 Day 组成:type Day struct {    gorm.Model    StudentID uint // parent id    Date string `sql:"size:255"`    Tasks []Task // has-many relation    Lessons []Lesson // has-many relation}
查看完整描述

1 回答

?
慕姐4208626

TA贡献1852条经验 获得超7个赞

您的Search Condition没有问题。您只需在第二次迭代的查询中提供多个 ID。一个在Where另一个在Find。


让我写一个像你这样的例子


ids := []int{1, 2}

var org database.Organization

for _, i := range ids {

    db, _ := connection.NewPGConnection(info)

    db = db.Debug().New()

    db.Where("id = ?", i).Find(&org)

}

这里,第一次迭代的 SQL 查询如下:


SELECT * FROM "organizations"  WHERE "organizations"."deleted_at" IS NULL AND ((id = '1'))

在第二次迭代中它将是:


SELECT * FROM "organizations"  WHERE "organizations"."deleted_at" IS NULL AND "organizations"."id" = '1' AND "organizations"."code" = 'mir' AND ((id = '2'))

为什么?因为,您使用了相同的变量day来读取行结果。


第一次,没关系。但是第二次,您的day 变量中已经有一个 ID。并且您在Where. 这就是为什么,它的运行查询有两个 id。


您实际上提供了两个id,一个在where子句中,另一个在中Find。


更改您的代码以每次都重新声明您的变量日。像这样。


ids := []int{1, 2}

for _, i := range ids {

    db, _ := connection.NewPGConnection(info)

    db = db.Debug().New()

    var org database.Organization  // <----- move your variable day here

    db.Where("id = ?", i).Find(&org)

}

每次都会使用新的和干净的变量。你的问题将得到解决。


谢谢。希望对你有帮助。



查看完整回答
反对 回复 2023-05-15
  • 1 回答
  • 0 关注
  • 180 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信