英文:
How can I get the maximum value of a specific day in 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" 风格的方法来获取特定表格的最大值,特别是涉及日期的情况。
英文:
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.
答案1
得分: 6
你可以在SQL中使用max
操作。也许这不是一个更“GORM”的方法来实现,但在我看来,这是一个更语义正确/吸引人的版本:
var result float64
row := db.Table("temperatures").Where("ts BETWEEN ? AND ?", start, end).Select("max(temperature)").Row()
err := row.Scan(&result)
你可以将这个方法作为Temperature结构体的一个方法,像这样:
func (t Temperature) MaxInRange(db *gorm.DB, start, end time.Time) (float64, err) {
var result float64
row := db.Table("temperatures").Where("ts BETWEEN ? AND ?", start, end).Select("max(temperature)").Row()
err := row.Scan(&result)
return result, err
}
英文:
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:
var result float64
row := db.Table("temperatures").Where("ts BETWEEN ? AND ?", start, end).Select("max(temperature)").Row()
err := row.Scan(&result)
You could make this a method of the Temperature struct like this:
func (t Temperature) MaxInRange(db *gorm.DB, start, end time.Time) (float64, err) {
var result float64
row := db.Table("temperatures").Where("ts BETWEEN ? AND ?", start, end).Select("max(temperature)").Row()
err := row.Scan(&result)
return result, err
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论