gpt4 book ai didi

go - Gorm与golang : Preload does not work as expected

转载 作者:行者123 更新时间:2023-12-01 22:22:25 27 4
gpt4 key购买 nike

我有以下结构

type Employee struct {
EmployeeID int64 `gorm:"primary_key;column:employee_id"`
EmployeeCode string `gorm:"column:employee_code"`
FirstName string `gorm:"column:first_name"`
LastName string `gorm:"column:last_name"`
DesignationID int64 `gorm:"column:designation_id;"`
Designation *Designation
}

type Designation struct {
DesignationID int64 `gorm:"primary_key;column:designation_id"`
DesignationName string `gorm:"column:designation_name"`
}

func GetEmployee(id int64) (*Employee, error) {
db := connection.GetConn() //get connection
defer db.Close()

employee := &Employee{}
err := db.Model(employee).Preload("Designation").Find(employee).Error
return employee, err
}

在表中,我有以下记录:
employee :
employee_id | employee_code | first_name | last_name | designation_id
1 | EMP1 | Raj | Mane | 1

designation:
designation_id | designation_name
1 | Engineer

参照指定表,employee.designation_id被标记为外键

当我调用函数GetEmployee时,它返回错误消息说 无法预加载模型的字段名称.Employee

我已经提到了许多与预载有关的问题,但是没有一个解决方案起作用。我认为其他工作案例之间的唯一区别是主要ID列名称。谁能建议正在发生的事情以及我在这里想念的是什么?

最佳答案

在GORM中,默认外键使用所有者的类型名称及其主键。
GORM提供了一种自定义外键的方法,例如:

type Employee struct {
EmployeeID int64 `gorm:"primary_key;column:employee_id"`
EmployeeCode string `gorm:"column:employee_code"`
FirstName string `gorm:"column:first_name"`
LastName string `gorm:"column:last_name"`
DesignationID int64 `gorm:"column:designation_id;"`
Designation *Designation `gorm:"foreignkey:DesignationID"`
}

关于go - Gorm与golang : Preload does not work as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62377218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com