登录
首页 >  Golang >  Go问答

修复不支持关系的架构错误:使用 gorm.Preload 的正确方法

来源:stackoverflow

时间:2024-02-11 13:18:24 370浏览 收藏

大家好,我们又见面了啊~本文《修复不支持关系的架构错误:使用 gorm.Preload 的正确方法》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

问题内容

我不断收到错误 technician:此结构模式和查询的模式 ticket 的关系不受支持?我该怎么做才能使此预加载查询正常工作?

或者至少如何调试这个问题?这个错误非常小,我已经阅读了 gorm 预加载页面 https://gorm.io/docs/preload.html,但不明白我做错了什么?

type Ticket struct {
    ID                  uuid.UUID  `json:"id"`
    CreatedAt           time.Time  `json:"createdAt"`
    UpdatedAt           time.Time  `json:"updatedAt"`
    ShopID              uuid.UUID  `json:"shopID"`
    Archived            bool       `json:"archived"`
    Services            []string   `json:"services"`
    Price               int        `json:"price"`
    Location            int        `json:"location"`
    Checkedout          bool       `json:"checkedout"`
    TechnicianID        uuid.UUID  `json:"technicianId"`
    Technician          Technician `json:"technician"`
    TechnicianPartnerID *uuid.UUID `json:"technicianPartnerId"`
    LastUpdatedBy       uuid.UUID  `json:"lastupdatedBy"`
}

type Technician struct {
    ID        uuid.UUID `json:"id"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`
    ShopID    uuid.UUID `json:"shopID"`
    Name      string    `json:"name"`
    Active    bool      `json:"active"`
}

dbQuery := t.Db.Orm.WithContext(ctx).Table("tickets").Preload("Technician")

正确答案


您没有使用标准的 gorm.model 作为键(来自文档):

type model struct {
  id        uint           `gorm:"primarykey"`
  createdat time.time
  updatedat time.time
  deletedat gorm.deletedat `gorm:"index"`
}

gorm 使用它来识别连接。

使用 gorm:"primarykey" 指示器更改密钥应该可以解决该问题。

或者替代方案:使用 gorm.model:

type Ticker struct {
    gorm.Model
    ShopID              uuid.UUID  `json:"shopID"`
    Archived            bool       `json:"archived"`
    Services            []string   `json:"services"`
    Price               int        `json:"price"`
    Location            int        `json:"location"`
    Checkedout          bool       `json:"checkedout"`
    TechnicianID        uuid.UUID  `json:"technicianId"`
    Technician          Technician `json:"technician"`
    TechnicianPartnerID *uuid.UUID `json:"technicianPartnerId"`
    LastUpdatedBy       uuid.UUID  `json:"lastupdatedBy"`
}

type Technician struct {
    gorm.Model
    ShopID    uuid.UUID `json:"shopID"`
    Name      string    `json:"name"`
    Active    bool      `json:"active"`
}

本篇关于《修复不支持关系的架构错误:使用 gorm.Preload 的正确方法》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>