Gorm中查询是否返回recordNotFound的情况总结

代码

package gorm_tests

import (
    "fmt"
    "github.com/gogf/gf/util/gconv"
    "github.com/stretchr/testify/require"
    "gorm.io/driver/mysql"
    "gorm.io/gorm"
    "testing"
    "time"
)

/*
CREATE TABLE `lottery`
(
    `id`          int(10) unsigned NOT NULL AUTO_INCREMENT,
    `activity_id` int(10) unsigned NOT NULL,
    `total_limit` int(10) unsigned NOT NULL,
    `daily_limit` int(10) unsigned NOT NULL,
    `create_at`   datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `update_at`   datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`),
    UNIQUE KEY `idx_activity_id` (`activity_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
*/

const (
    LotteryTableName = "lottery"
)

type Lottery struct {
    Id         uint32    `gorm:"column:id" json:"id"`
    ActivityId uint32    `gorm:"column:activity_id" json:"activityId"`          // 活动id,唯一索引
    TotalLimit uint32    `gorm:"column:total_limit" json:"totalLimit"`          // 总次数限制
    DailyLimit uint32    `gorm:"column:daily_limit" json:"dailyLimit"`          // 每日次数限制
    CreateAt   time.Time `gorm:"column:create_at;default:null" json:"createAt"` //  创建时间
    UpdateAt   time.Time `gorm:"column:update_at;default:null" json:"updateAt"` //  更新时间
}

func (l *Lottery) TableName() string {
    return LotteryTableName
}


func TestT6(t *testing.T) {

    dsn := "root:123@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
    db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
    require.Equal(t, err, nil)
    fmt.Println("db: ", db)

    lotteryModel := &Lottery{}

    // Notice Take方法: 如果记录不存在会报错 record not found
    // 翻译成的SQL语句: SELECT * FROM `lottery` WHERE id = 123 LIMIT 1
    //errTake := db.Table(LotteryTableName).Where("id = ?", 123).Take(lotteryModel).Error
    //require.Equal(t, errTake, nil)

    // Notice First方法: 如果记录不存在会报错 record not found
    // 翻译成的SQL语句(注意有Order By): SELECT * FROM `lottery` WHERE id = 123 ORDER BY `lottery`.`id` LIMIT 1
    //errFirst := db.Table(LotteryTableName).Where("id = ?", 123).First(lotteryModel).Error
    //require.Equal(t, errFirst, nil)

    // Notice Last方法: 如果记录不存在会报错 record not found
    // 翻译成的SQL语句(注意有Order By): SELECT * FROM `lottery` WHERE id = 123 ORDER BY `lottery`.`id` DESC LIMIT 1
    //errLast := db.Table(LotteryTableName).Where("id = ?", 123).Last(lotteryModel).Error
    //require.Equal(t, errLast, nil)

    // Notice Scan方法: 如果记录不存在不会报错!!但是的到的数据是一个 "零值"!!!
    errScan := db.Table(LotteryTableName).Where("id  = ?", 123).Scan(lotteryModel).Error
    require.Equal(t, errScan, nil)
    fmt.Printf("errScan: %v, lotteryModel: %v", errScan, gconv.String(lotteryModel))
    // errScan: <nil>, lotteryModel: {"id":0,"activityId":0,"totalLimit":0,"dailyLimit":0,"createAt":"0001-01-01T00:00:00Z","updateAt":"0001-01-01T00:00:00Z"}errFind: <nil>, lotteryModel: {"id":0,"activityId":0,"totalLimit":0,"dailyLimit":0,"createAt":"0001-01-01T00:00:00Z","updateAt":"0001-01-01T00:00:00Z"}

    // Notice Find方法: 如果记录不存在不会报错!但是会返回一个"空结构体",里面的值是结构体属性的"零值"!
    // Notice 同时Find方法里也可以放一个切片,进行多查~
    errFind := db.Table(LotteryTableName).Where("id = ?", 123).Find(lotteryModel).Error
    fmt.Printf("errFind: %v, lotteryModel: %v", errFind, gconv.String(lotteryModel))
    // errFind: <nil>, lotteryModel: {"id":0,"activityId":0,"totalLimit":0,"dailyLimit":0,"createAt":"0001-01-01T00:00:00Z","updateAt":"0001-01-01T00:00:00Z"}--- PASS: TestT6 (0.02s)
    require.Equal(t, errFind, nil)

}

~~~

posted on 2023-07-18 15:58  江湖乄夜雨  阅读(755)  评论(0编辑  收藏  举报