【问题标题】:need to define a foreign key for relations or it need to implement the Valuer/Scanner interface需要为关系定义外键或者需要实现 Valuer/Scanner 接口
【发布时间】:2020-12-15 19:51:07
【问题描述】:

如何解决这个问题?我遇到了这样的错误

struct gomar/campaign.Campaign 的字段 User 发现无效字段,需要为关系定义外键或者需要实现 Valuer/Scanner 接口

package campaign

import (
    "gomar/user"
    "time"
)

type Campaign struct {
    ID               int
    userID           int
    Name             string
    ShortDescription string
    Description      string
    Slug             string
    CreatedAt        time.Time
    UpdatedAt        time.Time
    CampaignImages   []CampaignImage
    User             user.User
}

type CampaignImage struct {
    ID         int
    CampaignID int
    FileName   string
    IsPrimary  int
    CreatedAt  time.Time
    UpdatedAt  time.Time
}

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    需要根据official doc! 为 user.User 添加标签。

    type Campaign struct {
        ID               int
        userID           int
        Name             string
        ShortDescription string
        Description      string
        Slug             string
        CreatedAt        time.Time
        UpdatedAt        time.Time
        CampaignImages   []CampaignImage
        User             user.User  `gorm:"foreignKey:Uid"`
    }
    
    type CampaignImage struct {
        ID         int
        CampaignID int
        FileName   string
        IsPrimary  int
        CreatedAt  time.Time
        UpdatedAt  time.Time
    }
    

    请同时为 user.User 执行迁移

    err := DB.AutoMigrate(&user.User{})
    if err != nil {
      panic("migration failed")
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 2019-01-07
      • 2012-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多