https://github.com/go-gorm/gorm/blob/b88148363a954f69fa680b152dfd96a94ffea1e1/scan.go#L179-L189
Here must be if
rather then for
. So now DB.ScanRows()
into int
variants silently eats all the rows and returns the last one.
Example:
func list[T any](tx *gorm.DB) ([]T, error) {
result := make([]T, 0)
rows, err := tx.Raw(
`(SELECT 10 AS x UNION SELECT 20 UNION SELECT 30) ORDER BY x`,
).Rows()
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var item T
err = tx.ScanRows(rows, &item)
if err != nil {
return nil, err
}
result = append(result, item)
}
return result, nil
}
func main() {
db, err := gorm.Open(...)
type Ref struct{ X int }
structs, err := list[Ref](tx)
if err != nil {...}
fmt.Printf("structs: %#v\n", structs)
ints, err := list[int](tx)
if err != nil {...}
fmt.Printf("ints: %#v\n", ints)
}
output:
structs: []main.Ref{main.Ref{X:10}, main.Ref{X:20}, main.Ref{X:30}}
ints: []int{30}
- go 1.24
- gorm 1.30 , 1.31
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question
template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨
Comment From: Vovan-VE
7612
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question
template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨