php editor Xinyi today introduces to you an important function of GORM, which is to return a result list or a result graph grouped by id. GORM is a powerful database access library that provides rich methods for querying and operating databases. By using GORM, we can easily get a list of results from the database and also group by id and return a graph of results. This function is very practical in actual development and can help us process database query results more conveniently. Next, let us learn how to use GORM to implement this function!
Essentially, using gormdb, my current code looks like this:
res = []*modelExample DB.Model(&modelExample{}). Order("task_id "). Find(res)
What I did with res is that I would manually loop and append the models with the same task_id to a list and then append this list to be processed. The reason I need to do this is because I need to perform some specific operations on specific columns that I need to extract and these operations cannot be performed in gorm.
However, is there a way to do this more efficiently, allowing me to return it like a list of lists, and then I can for loop and perform an operation on each list element?
You should be able to use the following code snippet to achieve your needs:
package main import ( "fmt" "gorm.io/driver/postgres" "gorm.io/gorm" ) type modelExample struct { TaskId int Name string } func main() { dsn := "host=localhost user=postgres password=postgres dbname=postgres port=5432 sslmode=disable" db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } db.AutoMigrate(&modelExample{}) // here you should populate the database with some data // querying res := make(map[int][]modelExample, 0) rows, err := db.Table("model_examples").Select("task_id, name").Rows() if err != nil { panic(err) } defer rows.Close() // scanning for rows.Next() { var taskId int var name string rows.Scan(&taskId, &name) if _, isFound := res[taskId]; !isFound { res[taskId] = []modelExample{{taskId, name}} continue } res[taskId] = append(res[taskId], modelExample{taskId, name}) } // always good idea to check for errors when scanning if err = rows.Err(); err != nil { panic(err) } for _, v := range res { fmt.Println(v) } }
After completing the initial setup, let’s take a closer look at the query part.
First, you will get all the records from the table. The records you get are stored in the rows
variable.
In the for
loop, you scan all records. Each record will be added as a new map entry or appended to an existing entry if taskid
already exists in the map.
This is the simplest way to create different lists based on specific columns (e.g. taskid
). Actually, from my understanding, you need to split the records instead of grouping them using aggregate functions (e.g. count
, sum
, etc.).
The other code I've added is just for clarity.
If this solves your problem or you need something else, please let me know, thanks!
The above is the detailed content of GORM returns a list of results or a graph of results grouped by id. For more information, please follow other related articles on the PHP Chinese website!