使用updated_at选择WHERE是错误的

问题描述 投票:-1回答:2

预计此代码结果是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设置发生的。 我怎么能解决这个问题?

UPDATE粘贴功能代码

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,
    }
}

photos是正确的。 onedays不正确......

go go-gorm
2个回答
1
投票

这里:

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,因此它不再是空的。在第4行,你写的是photos async-ly,这会导致数据竞争,如果有多个goroutines,它会搞砸。

您应该在func中重新声明两个数组:

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

0
投票

正如您在GORM获得的响应中所看到的,update_at值包含时区(+09:00部分),而数据库中的值则没有,因此这些值可以作为UTC处理,也可以作为数据库中配置的默认时区处理服务器。

您应该检查数据库与运行代码的主机之间的时区差异。

© www.soinside.com 2019 - 2024. All rights reserved.