go - SELECT WHERE with updated_at 是错误的

标签 go go-gorm

预期此代码结果为 null 但我得到的不是 null。
rDB.Where("user_id = ? AND updated_at > ?", userID, date).Find(&onedays)

date := "2018-01-04 23:18:00" Onedays 表中有一些记录。

+----+---------+------------+------------+---------------------+
| id | user_id | save_state | date       | updated_at          |
+----+---------+------------+------------+---------------------+
|  1 |      44 |          0 | 1514214001 | 2018-01-04 21:25:05 |
|  2 |      44 |          0 | 1514214001 | 2018-01-04 22:07:55 |
|  3 |      15 |          1 | 1514300400 | 2018-01-04 23:17:49 |
+----+---------+------------+------------+---------------------+

返回它的代码是:

{
"onedays": [
    {
        "id": 1,
        "user_id": 44,
        "save_state": false,
        "date": 1514214001,
        "updated_at": "2018-01-04T21:25:05+09:00"
    },
    {
        "id": 2,
        "user_id": 44,
        "save_state": false,
        "date": 1514214001,
        "updated_at": "2018-01-04T22:07:55+09:00"
    }
],
"photos": null
}

但是我执行这个查询,返回是空的。
SELECT * FROM Onedays WHERE user_id = 44 AND updated_at > '2018-01-04 23:18:00'

这个问题可能是gorm设置引起的。
我该如何解决这个问题?

更新粘贴的函数代码

func getDiff(userID, date string) interface{} {
    var wg sync.WaitGroup

    var onedays []model.OnedayDiff
    var photos []model.PhotoDiff
    var resPhotos []model.PhotoDiff

    _, rDB := lib.DB()
    rDB.Where("user_id = ? AND updated_at > ?", userID, date).Find(&onedays)

    funcs := []func(){
        // Photo
        func() {
            rDB.Where("user_id = ?", userID).Find(&onedays)
            for _, v := range onedays {
                rDB.Where("oneday_id = ? AND updated_at > ?", v.ID, date).Find(&photos)
                resPhotos = append(resPhotos, photos...)
            }
        },
    }
    for _, sleep := range funcs {
        wg.Add(1)

        go func(function func()) {
            defer wg.Done()
            function()
        }(sleep)
    }
    wg.Wait()

    return map[string]interface{}{
        "onedays": onedays,
        "photos":  resPhotos,
    }
}

照片 是正确的。 onedays 不正确...

最佳答案

这里:

func() {
    rDB.Where("user_id = ?", userID).Find(&onedays)
    for _, v := range onedays {
        rDB.Where("oneday_id = ? AND updated_at > ?", v.ID, date).Find(&photos)
        resPhotos = append(resPhotos, photos...)
    }
},

您在第二行中重复使用了 onedays slice ,因此它不再是空的。在第 4 行中,您正在异步写入 photos,这会导致数据争用,如果有多个 goroutine,就会搞砸。

你应该在函数中重新声明两个数组:

func() {
    var onedays []model.OnedayDiff
    var photos []model.PhotoDiff
    //other codes
}

关于go - SELECT WHERE with updated_at 是错误的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48098042/

相关文章:

html - r.From ["username"] 给出空值

postgresql - 使用 Gorm 插入和选择 PostGIS 几何

go - 更改模型,但数据库未相应更改

arrays - 在 Go 中解码 JSON Array of arrays

go - 是否有一个 golang redis 客户端可以自动检测 pubsub 的新分片?

go - 使用 Gorm 将值从一列映射到单独表中的另一列

postgresql - 使用 GORM 和 Postgresql 如何设置搜索路径?

json - 用sql.NullFloat64包装json.Number

unit-testing - 需要文件的单元测试方法