为结构字段找到无效字段,需要为关系定义外键或需要实现 Valuer/Scanner 接口

Man*_*Man 6 go go-gorm

省略不工作。

检索错误:

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:"-"`
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)

小智 5

在 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:"-"`
}
Run Code Online (Sandbox Code Playgroud)

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

DeliveryZone []*DeliveryZone json:",omitempty" gorm:"foreignKey:RestaurantId"
Run Code Online (Sandbox Code Playgroud)


Max*_*xim 4

尝试

DeliveryZone []*DeliveryZone `gorm:"-"`
Run Code Online (Sandbox Code Playgroud)

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