Home > Backend Development > Golang > GORM returns a list of results or a graph of results grouped by id

GORM returns a list of results or a graph of results grouped by id

王林
Release: 2024-02-12 11:54:08
forward
1201 people have browsed it

GORM 返回结果列表或按 id 分组的结果图

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!

Question content

Essentially, using gormdb, my current code looks like this:

res = []*modelExample

DB.Model(&modelExample{}).
        Order("task_id ").
        Find(res)
Copy after login

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?

Workaround

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)
    }
}
Copy after login

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!

Related labels:
source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template