How to insert a GORM model with deeply nested one-to-many models

Viewed 54

I have 3 struct models corresponding to 3 DB tables.

Book model

type Book struct {
   ID      uuid.UUID
   Pages   []*Page
}

Page model

type Page struct {
   ID        uuid.UUID
   BookID    string
   PageNum   int
   Words     []*Word
}

Word model

type Word struct {
   ID       uuid.UUID
   PageID   uuid.UUID
   Letters  []byte
}

One Book can have many Pages. One Page can have many Words.

I am trying to insert a single hydrated Book struct into my Book table, and allow GORM to populate the several rows for the Page and Word tables. Based on the examples in the GORM has many documentation it seems this can be done with one create() call and association will be inferred by the default naming convention. But when I call db.Create(&hydratedBook) only the Book table is inserted into.

Debug output:

INSERT  INTO "book" ("id","created_at","updated_at","delete_requested_at") 
VALUES ('95B9A964-7227-44B1-AA32-C5BCEDCE0857','2022-07-08 22:01:36','2022-07-08 22:01:36',NULL) 
RETURNING "book"."id"

Any feedback is greatly appreciated.

0 Answers
Related