To obtain query count results when working with Gorm for database operations, we can use the Count method. This method returns the total number of records matching specific criteria. Below, I will demonstrate with a concrete example how to use Gorm in Go to retrieve query counts.
Assume we have a user table users, and we aim to compute the total number of users in it.
First, ensure that you have installed and imported the Gorm package, and set up the database connection. Below is the basic model and database connection setup:
gopackage main import ( "fmt" "gorm.io/driver/sqlite" "gorm.io/gorm" ) type User struct { gorm.Model Name string } func main() { db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) if err != nil { panic("failed to connect database") } // This is auto-migration mode; use as needed in actual development db.AutoMigrate(&User{}) // Example: Add user data db.Create(&User{Name: "Alice"}) db.Create(&User{Name: "Bob"}) // Retrieve count result var count int64 db.Model(&User{}).Count(&count) fmt.Printf("Users count: %d\n", count) }
In the preceding code, we define a User struct that corresponds to the users table. We use db.Model(&User{}) to specify the model as User, and then invoke the Count(&count) method to store the result in the count variable.
Executing this program will display the count of records in the user table. This method is ideal for obtaining the count of records in a table or after applying specific filtering conditions.
Note that when using the Count method, the variable must be a pointer of type int64, as Gorm stores the count result in it.
The above provides an example and explanation of obtaining query counts using Gorm in Go.