Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invalid field found for struct field , need to define a foreign key for relations or it need to implement the Valuer/Scanner interface

Tags:

go

go-gorm

Omit not working.

Retrieve Error:

invalid field found for struct deliveryFood/models.Restaurant's field DeliveryZone, need to define a foreign key for relations or it need to implement the Valuer/Scanner interface

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
like image 505
Man Avatar asked Sep 09 '20 11:09

Man


2 Answers

Change RestaurantId to RestaurantID in DeliveryZone struct.

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

Or you can define the foreignkey manually by adding foreignKey tag in Restaurant struct. e.g.

DeliveryZone []*DeliveryZone json:",omitempty" gorm:"foreignKey:RestaurantId"
like image 126
KevinLiu Avatar answered Sep 19 '22 15:09

KevinLiu


try

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

https://gorm.io/docs/models.html -> ctrl+F -> ignore this field

like image 41
Maxim Avatar answered Sep 19 '22 15:09

Maxim