【问题标题】:invalid field found for struct field , need to define a foreign key for relations or it need to implement the Valuer/Scanner interface为 struct field 找到无效字段,需要为关系定义外键或需要实现 Valuer/Scanner 接口
【发布时间】:2020-09-09 11:16:29
【问题描述】:

忽略不工作。

检索错误:

为 struct deliveryFood/models.Restaurant 的字段找到无效字段 DeliveryZone,需要为关系定义外键或者需要 实现 Valuer/Scanner 接口

type Restaurant struct {
ID uint
Name string `json:"name"`
EmployeeId uint `json:"employee_id"`
Phone string `json:"phone"`
Address string `json:"address"`
ImagesUrl *string `json:"images_url"`
Position string `json:"position"`
WorkDays string `json:"work_days"`
StartWorkTime string `json:"start_work_time"`
EndWorkTime string `json:"end_work_time"`
Blocked bool `json:"blocked"`
DeliveryZone []*DeliveryZone `json:",omitempty"`
}

type DeliveryZone struct {
ID uint `json:"id"`
RestaurantId uint `json:"restaurant_id"`
Zone string `json:"zone"`
Price float32 `sql:"-"`
}
err := GetDB().Omit(clause.Associations).Model(Restaurant{}).Create(map[string]interface{} {
   "name": rest.Name,
   "EmployeeId": rest.EmployeeId,
   "Phone": rest.Phone,
   "Address": rest.Address,
   "ImagesUrl": rest.ImagesUrl,
   "WorkDays": rest.WorkDays,
   "StartWorkTime": rest.StartWorkTime,
   "EndWorkTime": rest.EndWorkTime,
   "Blocked": rest.Blocked,
   "Position": clause.Expr{
      SQL: "ST_GeomFromText(?)",
      Vars: []interface{}{fmt.Sprintf("POINT((%s))", rest.Position)},
   },
}).Error

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    在 DeliveryZone 结构中将 RestaurantId 更改为 RestaurantID。

    type Restaurant struct {
        ID uint
        Name string `json:"name"`
        EmployeeId uint `json:"employee_id"`
        Phone string `json:"phone"`
        Address string `json:"address"`
        ImagesUrl *string `json:"images_url"`
        Position string `json:"position"`
        WorkDays string `json:"work_days"`
        StartWorkTime string `json:"start_work_time"`
        EndWorkTime string `json:"end_work_time"`
        Blocked bool `json:"blocked"`
        DeliveryZone []*DeliveryZone `json:",omitempty"`
    }
    
    type DeliveryZone struct {
        ID uint `json:"id"`
        RestaurantID uint `json:"restaurant_id"`
        Zone string `json:"zone"`
        Price float32 `sql:"-"`
    }
    

    或者您可以通过在 Restaurant 结构中添加 foreignKey 标签来手动定义外键。例如

    DeliveryZone []*DeliveryZone json:",omitempty" gorm:"foreignKey:RestaurantId"
    

    【讨论】:

      【解决方案2】:

      试试

      DeliveryZone []*DeliveryZone `gorm:"-"`
      

      https://gorm.io/docs/models.html -> ctrl+F -> 忽略此字段

      【讨论】:

      • 谢谢,但我并不总是想忽略这个字段,只是在这种情况下。可能还有其他解决方案吗?
      • 我无法理解您的情况以及您最初想要什么,请详细说明您的问题
      • 忽略将如何解决这个问题?它只会跳过错误和所需的行为......
      猜你喜欢
      • 1970-01-01
      • 2021-08-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-26
      • 2012-01-15
      • 2019-01-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多