In my mysql db I have table "restaurant". This table has field "position" with type POINT. So, when I try to insert data in to table using customized data type like in docs https://gorm.io/docs/create.html#Create-From-SQL-Expr/Context-Valuer and to get inserted id, but I got error:
"sql: converting argument $6 type: unsupported type models.Point, a struct"
I'm new in go and sorry for my English.
Code:
Model
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 Point `json:"position" gorm:"type:Point"`
WorkDays string `json:"work_days"`
StartWorkTime string `json:"start_work_time"`
EndWorkTime string `json:"end_work_time"`
Blocked bool `json:"blocked"`
}
Point type
type Point struct {
LatLong string `json:"lat_long"`
//Lat float64
//Long float64
}
func (p *Point) Scan(v interface{}) error {
fmt.Printf("Scan value %v", v)
return nil
}
func (p Point) GormDataType() string {
return "geometry"
}
func (p Point) GormValue(ctx context.Context, db *gorm.DB) clause.Expr {
return clause.Expr{
SQL: "ST_PointFromText(?, 4326)",
Vars: []interface{}{fmt.Sprintf("POINT(%s)", p.LatLong)},
}
}
body request data:
{
"name": "Restaurant 1",
"employee_id": 9,
"phone": "123465",
"address": "Test Address 91",
"work_days": "sdfsfsd",
"start_work_time": "00:00:00",
"end_work_time": "00:00:00",
"position": {
"lat_long": "38.590559 68.755866"
}
}
Calling method after parsing body to Restaurant type
func NewRestaurant(restaurant *Restaurant) (uint, error) {
err := GetDB().Create(restaurant).Error
if err != nil {
return 0, err
}
return restaurant.ID, nil
}
dependency
import (
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
gorm build this query :
INSERT INTO `restaurant`
(`name`,`employee_id`,`phone`,`address`,`images_url`,`position`,`work_days`,`start_work_time`,`end_work_time`,`blocked`)
VALUES
("Restaurant 1",9,"123465","Test Address 91",NULL,"{38.590559 68.755866}","sdfsfsd","00:00:00","00:00:00",false)