Gorm与golang。预加载没有达到预期效果

问题描述 投票:0回答:1

我有以下结构

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被标记为外键,指向designation表。

当我调用函数GetEmployee时,它返回错误信息说 不能为model.Employee预加载字段Designation。

我参考了很多与Preload相关的问题,但都没有解决。我认为其他工作情况之间的唯一区别是主ID列名。谁能告诉我发生了什么,我遗漏了什么?

go gorm preload
1个回答
0
投票

在GORM中,默认的外键使用所有者的类型名加上主键,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"`
}
© www.soinside.com 2019 - 2024. All rights reserved.