go-gorm / gorm

The fantastic ORM library for Golang, aims to be developer friendly
https://gorm.io
MIT License
36.46k stars 3.9k forks source link

Scan row into multiple structs #6986

Open elbek opened 4 months ago

elbek commented 4 months ago

How to scan a row into multiple structs

The document you expected this should be explained

This code used to work with 1.20 go version

func MultiScan(db *gorm.DB, rows *sql.Rows, items ...interface{}) error {
    for _, item := range items {
        err := db.ScanRows(rows, item)
        if err != nil {
            return err
        }
    }
    return nil
}

It fails to work now giving error scan called without calling next (closemuscanhold) in 1.22

Expected answer

How can we scan a row into multiple struct. Something like this didn't work:

func MultiScan1(db *gorm.DB, rows *sql.Rows, items ...interface{}) error {
    var records []any
    records = append(records, items...)
    err := db.ScanRows(rows, &records)
    if err != nil {
        return err
    }
    return nil
}

I know I can create a struct and embed all these structs and scan into it, but this is no go for us. We have hundred of places and scan scans into 5-10 structs often.

Looking a way to fix multi scan in a way that works.

elbek commented 4 months ago

@jinzhu Any idea how can we accomplish this?

Viv-ek-Pandey commented 2 months ago

@elbek Hi , I ran into the same problem , did you find anything ? What is causing this ? or is there a workaround ?