使用 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
}
慕姐4208626
相关分类