【问题标题】:Error when using preload gorm golang, it's not running the preload table i need使用预加载 gorm golang 时出错,它没有运行我需要的预加载表
【发布时间】:2021-07-08 08:12:30
【问题描述】:

我尝试在 gorm golang 中学习和定义模型 但我遇到了这个问题......不知道如何找到问题。 首先,我在数据库中创建了 2 个表名 User 和 Schedule 这是模型

type User struct {
    UserId       int    `json:",omitempty" gorm:"primaryKey"`
    UserName     string `json:",omitempty"`
    UserPassword string `json:"-"`
    UserEmail    string `json:",omitempty"`
    UserFullName string `json:",omitempty"`
    Schedule []*Schedule `gorm:"foreignKey:UserId" json:"working_schedule"`
}
type Schedule struct {
    ScheduleId      int `gorm:"primaryKey"`
    ScheduleDate    int
    ScheduleStart   int
    ScheduleEnd     int
    ScheduleType    int
    ScheduleCreated int
    UserId          int
}

我还在 golang 中执行此代码,以通过我获得的 id 进行查询以获取特定用户的所有日程安排。

Preload("Schedule").Table("user").Find(&user, "user_id=?", id)

但是当全部显示结果时,working_schedule 为空。我试图调试上面的代码,但发现它只是从用户中运行一个选择......而不是在计划中

SELECT * FROM `user` WHERE user_id=1

我知道我做错了什么。请帮我。类型

【问题讨论】:

    标签: go


    【解决方案1】:

    由于您将结构命名为Schedulego-gorm 将尝试查找名为schedules 的表,因为它使用复数形式的snake-case 约定。如果不成功,则在进行预加载时不会为其创建查询。

    如果您的数据库表名为schedule,则必须实现Tabler 接口(可能低于Schedule 结构的定义)。

    func (Schedule) TableName() string {
        return "schedule"
    }
    

    您可以在此here 上找到更多信息。

    【讨论】:

    • 嗨。感谢您的回答...但是在我的数据库中已经有一个数据库名称计划
    • 我将修改我的答案以使用 schedule 数据库表名。
    • 好吧...所以现在它会找到表名:schedule 对吗?我需要的是实现要使用的tabler?但是当我使用 .Debug() 时,没有任何事情发生,例如:找不到表 Schedules 等。所以很难知道查询是否已构建...
    • 如果你的数据库表名是schedule,那么你需要这个Tabler接口实现。如果数据库名称为schedules,则不需要此实现。
    • 但是当我将表名更改为时间表时。然后再次运行代码……还是和之前的结果一样
    猜你喜欢
    • 2017-04-23
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多