无法使用 *DB.Rows() 获取所有行

Cannot fetch all rows with *DB.Rows()

我是 gorm 的新手,所以如果我有什么误解,请指出。

我正在使用 MySQL 编写小型应用程序,我决定使用 gorm 作为 ORM。 源代码和输出如下。

package main

import (
    "fmt"
    "log"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Group struct {
    gorm.Model
    Name string `gorm:"not null;unique"`
}

func openDB() *gorm.DB {
    user := "ipmonitor"
    password := "testpassword"
    database := "ipmonitor"

    mysqlURL := "%s:%s@/%s?charset=utf8mb4&parseTime=True&loc=Local"

    db, err := gorm.Open("mysql", fmt.Sprintf(mysqlURL, user, password, database))
    if err != nil {
        log.Fatalln(err)
    }

    return db
}

func initDB(db *gorm.DB) {
    db = db.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4")
    db.AutoMigrate(&Group{})

    result := db.Create(&Group{Name: "foo"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
    result = db.Create(&Group{Name: "bar"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
    result = db.Create(&Group{Name: "baz"})
    if result.Error != nil {
        log.Fatalln(result.Error)
    }
}

func main() {
    db := openDB()
    db.LogMode(true)
    initDB(db)

    records := db.Find(&Group{})
    if records.Error != nil {
        log.Fatalln(records.Error)
    }

    log.Printf("%d rows found.", records.RowsAffected)
    rows, err := records.Rows()
    if err != nil {
        log.Fatalln(err)
    }
    defer rows.Close()

    for rows.Next() {
        var group Group
        err := db.ScanRows(rows, &group)
        if err != nil {
            log.Fatalln(err)
        }

        log.Printf("%+v\n", group)
    }
    if rows.Err() != nil {
        log.Fatalln(rows.Err())
    }
}

输出

(dbtest.go:33)
[2018-07-30 18:12:33]  [9.96ms]  CREATE TABLE `groups` (`id` int unsigned AUTO_INCREMENT,`created_at` timestamp NULL,`updated_at` timestamp NULL,`deleted_at` timestamp NULL,`name` varchar(255) NOT NULL UNIQUE , PRIMARY KEY (`id`)) ENGINE=InnoDB CHARSET=utf8mb4
[0 rows affected or returned ]

(dbtest.go:33)
[2018-07-30 18:12:33]  [6.95ms]  CREATE INDEX idx_groups_deleted_at ON `groups`(deleted_at)
[0 rows affected or returned ]

(dbtest.go:35)
[2018-07-30 18:12:33]  [0.89ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'foo')
[1 rows affected or returned ]

(dbtest.go:39)
[2018-07-30 18:12:33]  [0.99ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'bar')
[1 rows affected or returned ]

(dbtest.go:43)
[2018-07-30 18:12:33]  [0.88ms]  INSERT INTO `groups` (`created_at`,`updated_at`,`deleted_at`,`name`) VALUES ('2018-07-30 18:12:33','2018-07-30 18:12:33',NULL,'baz')
[1 rows affected or returned ]

(dbtest.go:54)
[2018-07-30 18:12:33]  [0.63ms]  SELECT * FROM `groups`  WHERE `groups`.`deleted_at` IS NULL
[3 rows affected or returned ]
2018/07/30 18:12:33 3 rows found.

(dbtest.go:60)
[2018-07-30 18:12:33]  [0.77ms]  SELECT * FROM `groups`  WHERE `groups`.`deleted_at` IS NULL AND `groups`.`id` = '3'
[0 rows affected or returned ]
2018/07/30 18:12:33 {Model:{ID:3 CreatedAt:2018-07-30 18:12:34 +0900 JST UpdatedAt:2018-07-30 18:12:34 +0900 JST DeletedAt:<nil>} Name:baz}

MySQL

mysql> select * from groups;
+----+---------------------+---------------------+------------+------+
| id | created_at          | updated_at          | deleted_at | name |
+----+---------------------+---------------------+------------+------+
|  1 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | foo  |
|  2 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | bar  |
|  3 | 2018-07-30 18:12:34 | 2018-07-30 18:12:34 | NULL       | baz  |
+----+---------------------+---------------------+------------+------+
3 rows in set (0.00 sec)

我希望 *DB.Find().Rows() 方法 return 多行,但似乎只有 return 最后一行。

根据gorm调试输出,似乎在执行SELECT语句时添加了未指定的条件。

谷歌搜索后,我无法找出问题的原因。 为什么我的代码不起作用?

谢谢。

您可以试试这个替代方法:

var records []Group
db.Find(&records)

所有数据都将在 records 中作为数组提供。

如需处理错误:

if err := db.Find(&records).Error; err != nil {
  log.Fatalln(err)
}
log.Printf("%d rows found.", len(records))