Gorm预加载产生不明确的列错误

j9per5c4  于 2023-01-06  发布在  Go
关注(0)|答案(1)|浏览(138)

我有以下结构体

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"`
}

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(employees).Preload("Designation", func(db *gorm.DB) *gorm.DB {
        return db.Join("INNER JOIN employees ON employees.designation_id = designations.id").Order("employees.first_name DESC")
    }).Find(employee).Error
    return employee, err
}

生成的查询为

SELECT * FROM employees;
SELECT * FROM designations INNER JOIN employees ON employees.designation_id = designations.id WHERE id IN (1,2) order by employees.first_name DESC;

我有一个连接,它与我在上面的函数中所写的类似。这里我不能只执行连接,但在实际情况中,我知道连接是必需的,并且预加载表和连接表都有id字段。由于两个表有相同的列名,即id,在这种情况下,MYSQL抛出错误消息
Error 1052: Column 'id' in where clause is ambiguous
我在gorm v1.9.16中遇到了这个问题
我没有找到任何资源提到类似的问题。我们如何解决这个问题?

相关问题