如何获得 Gorm 中特定日期的最大值?
我已经写了以下代码,以获取使用Gorm的每日最大值。
- 我经过当前的时间,开始一天的开始和结束。
- 我在一天的开始和结束之间选择所有值。
- 我订购温度并获得第一个。
我的代码:
func GetDailyMaxTemperature(ts time.Time) (*Temperature, error) {
temp:= &Temperature{}
start, end := getStartAndEndOfDay(ts)
if tx := db.Where("ts BETWEEN ? AND ?", start, end).Order("temperature ASC").First(temp); tx.Error != nil {
return temp, tx.Error
}
return temp, nil
func getStartAndEndOfDay(ts time.Time) (time.Time, time.Time) {
dayStart := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, ts.Location())
dayEnd := time.Date(ts.Year(), ts.Month(), ts.Day(), 23, 59, 59, 999, ts.Location())
return dayStart, dayEnd
}
此代码有效,但是我对此并不满意,并且想知道是否有更多的“ Gorm-ish”方法获得特定表的最大值,尤其是在涉及日期时。
I have written following code to get the daily maximum of a certain value with GORM.
- I pass the current time and get the day's start and end.
- I select all values between the day's start and end.
- I order the temperatures and get the first.
My Code:
func GetDailyMaxTemperature(ts time.Time) (*Temperature, error) {
temp:= &Temperature{}
start, end := getStartAndEndOfDay(ts)
if tx := db.Where("ts BETWEEN ? AND ?", start, end).Order("temperature ASC").First(temp); tx.Error != nil {
return temp, tx.Error
}
return temp, nil
func getStartAndEndOfDay(ts time.Time) (time.Time, time.Time) {
dayStart := time.Date(ts.Year(), ts.Month(), ts.Day(), 0, 0, 0, 0, ts.Location())
dayEnd := time.Date(ts.Year(), ts.Month(), ts.Day(), 23, 59, 59, 999, ts.Location())
return dayStart, dayEnd
}
This code works, however I am not very satisfied with it and wonder if there are more "GORM-ish" ways to get a maximum value of a certain table especially when there are dates involved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您可以在SQL中使用
max
操作。也许不是一种更“ gorm”的方法,但我认为在语义上更正确/有吸引力的版本:您可以将其作为这样的温度结构的方法:
You could use the
max
operation in SQL. Maybe not a more 'GORM' way to do this, but in my opinion a more semantically correct/appealing version:You could make this a method of the Temperature struct like this: