2020-05-11 11:01:28 +02:00
|
|
|
package entity
|
2020-05-09 11:00:22 +02:00
|
|
|
|
2020-05-30 14:52:47 +02:00
|
|
|
import (
|
|
|
|
"github.com/jinzhu/gorm"
|
|
|
|
)
|
|
|
|
|
2022-04-10 14:38:51 +02:00
|
|
|
// Count returns the number of records for a given a model and key values.
|
|
|
|
func Count(m interface{}, keys []string, values []interface{}) int {
|
|
|
|
if m == nil || len(keys) != len(values) {
|
|
|
|
log.Debugf("entity: invalid parameters (count records)")
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
db, count := UnscopedDb(), 0
|
2022-04-10 14:38:51 +02:00
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
stmt := db.Model(m)
|
2022-04-10 14:38:51 +02:00
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
// Compose where condition.
|
2022-04-10 14:38:51 +02:00
|
|
|
for k := range keys {
|
|
|
|
stmt.Where("? = ?", gorm.Expr(keys[k]), values[k])
|
|
|
|
}
|
|
|
|
|
2022-04-16 12:39:47 +02:00
|
|
|
// Fetch count from database.
|
2022-04-10 14:38:51 +02:00
|
|
|
if err := stmt.Count(&count).Error; err != nil {
|
|
|
|
log.Debugf("entity: %s (count records)", err)
|
|
|
|
return -1
|
|
|
|
}
|
|
|
|
|
|
|
|
return count
|
|
|
|
}
|