Search code examples
gogo-gorm

How to fix unsupported relations for schema error with gorm.Preload


I keep getting error Technician: unsupported relations for schema Ticket for this struct schema and query? What can I do to get make this Preload query works?

Or at least how can debug this issue? The error is pretty bare minimal and I have read the gorm preload page https://gorm.io/docs/preload.html, and don't get what I did wrong?

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")

Solution

  • You are not using the standard gorm.Model for the keys (from the docs):

    type Model struct {
      ID        uint           `gorm:"primaryKey"`
      CreatedAt time.Time
      UpdatedAt time.Time
      DeletedAt gorm.DeletedAt `gorm:"index"`
    }
    

    Gorm uses this to identify joins.

    Changing your keys with the gorm:"primaryKey" indicator should fix the issue.

    Or alternative: use 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"`
    }