Table of Contents
Question content
Workaround
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

Feb 12, 2024 am 11:54 AM
aggregate function

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between sum and count in oracle The difference between sum and count in oracle May 02, 2024 pm 11:09 PM

SUM in Oracle is used to calculate the sum of non-null values, while COUNT counts the number of non-null values ​​of all data types, including duplicate values.

How to write grouping function in mysql How to write grouping function in mysql Apr 29, 2024 am 04:30 AM

The grouping function in MySQL is used to calculate aggregate values ​​by grouping a data set. Commonly used functions are: SUM: Calculate the sum of the values ​​in the specified column COUNT: Calculate the number of non-NULL values ​​in the specified column AVG: Calculate the average value of the values ​​in the specified column MIN: Calculate the minimum value in the specified column MAX: Calculate the number of non-NULL values ​​in the specified column the maximum value of

What does group by mean in sql What does group by mean in sql Apr 29, 2024 pm 02:48 PM

GROUP BY is an aggregate function in SQL that is used to group data based on specified columns and perform aggregation operations. It allows users to: Group data rows based on specific column values. Apply an aggregate function (such as sum, count, average) to each group. Create meaningful summaries from large data sets, perform data aggregation and grouping.

What are the aggregate functions in sql What are the aggregate functions in sql May 02, 2024 am 01:12 AM

Aggregate functions in SQL are used to calculate and return a single value for a set of rows. Common aggregation functions include: Numeric aggregation functions: COUNT(), SUM(), AVG(), MIN(), MAX() Row set aggregation functions: GROUP_CONCAT(), FIRST(), LAST() Statistical aggregation functions: STDDEV (), VARIANCE() optional aggregate functions: COUNT(DISTINCT), TOP(N)

How sum in sql is calculated How sum in sql is calculated May 09, 2024 am 09:27 AM

The SQL SUM function calculates the sum of a set of numbers by adding them together. The operation process includes: 1. Identifying the input value; 2. Looping the input value and converting it into a number; 3. Adding each number to accumulate a sum; 4. Returning the sum result.

How to use count function in oracle How to use count function in oracle Apr 30, 2024 am 07:39 AM

The COUNT function in Oracle is used to count non-null values ​​in a specified column or expression. The syntax is COUNT(DISTINCT <column_name>) or COUNT(*), which counts the number of unique values ​​and all non-null values ​​respectively.

How to use avg in mysql How to use avg in mysql May 01, 2024 pm 09:16 PM

MySQL's AVG() function is used to calculate the average of numeric values. It supports multiple usages, including: Calculate the average quantity of all sold products: SELECT AVG(quantity_sold) FROM sales; Calculate the average price: AVG(price); Calculate the average sales volume: AVG(quantity_sold * price). The AVG() function ignores NULL values, use IFNULL() to calculate the average of non-null values.

How to use sum function in sql How to use sum function in sql May 02, 2024 am 12:01 AM

The SUM() function in SQL is used to calculate the sum of numeric columns. It can calculate sums based on specified columns, filters, aliases, grouping and aggregation of multiple columns, but only handles numeric values ​​and ignores NULL values.

See all articles