Your Question
I have model like
type Rect struct {
X1 float64 `json:"x1"`
Y1 float64 `json:"y1"`
X2 float64 `json:"x2"`
Y2 float64 `json:"y2"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
type Position struct {
Bounding Rect `gorm:"embedded;embeddedPrefix:bounding_"`
Rects []Rect // how to save it?
Page int32
}
type Highlight struct {
Id string `gorm:"primaryKey"`
Content string
Color string
ImageId string
UserId string
BookId string
Page int32
Position Position `gorm:"embedded;embeddedPrefix:position_"`
Type HighlightType
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt gorm.DeletedAt `gorm:"index"`
}
Store code
func (s *HighlightStore) GetHighlight(ctx context.Context, id string) (*types.Highlight, error) {
var highlight types.Highlight
s.db.First(&highlight, "id = ?", id)
return &highlight, nil
}
func (s *HighlightStore) CreateHighlight(ctx context.Context, highlight *types.Highlight) (*types.Highlight, error) {
result := s.db.Create(highlight)
if result.Error != nil {
return nil, result.Error
}
return highlight, nil
}
func NewHighlightStore(connect config.PostgresConnectString) *HighlightStore {
db, err := gorm.Open(postgres.Open(string(connect)), &gorm.Config{})
if err != nil {
fmt.Println("highlight db connect failed: ", err)
}
db.AutoMigrate(&types.Highlight{}, &types.Position{}, &types.Rect{})
return &HighlightStore{
db: db,
}
}
After create highlight like (I sure I convert the value from json to correct value object)
{
"highlight": {
"id": "53",
"content": "hello",
"color": "do nulla",
"image_id": "http://dummyimage.com/400x400",
"user_id": "11",
"book_id": "2",
"page": 1,
"position": {
"bounding": {
"x1": 73,
"y1": 87,
"x2": 10,
"y2": 65,
"width": 91,
"height": 32
},
"rects": [
{
"x1": 65,
"y1": 53,
"x2": 48,
"y2": 88,
"width": 43,
"height": 20
}
],
"page": 1
},
"type": "HIGHLIGHT_TYPE_TEXT"
}
}
I got [error] invalid embedded struct for Highlight's field Position, should be struct, but got types.Position
The document you expected this should be explained
Expected answer
I want to know how to code my case. How to save a nest model or best practices