I want to use gorm
the use a many to one relationship in my project.
My struct
s are like this:
type Book struct {
ID uint
Title string
Subtitle string
Chapters []Chapter `gorm:"foreignkey:BookID;association_foreignkey:ID"`
} }
// TableName is book
func (Book) TableName() string {
return "book"
}
// Chapter of books
type Chapter struct {
ID uint
BookID string
Chapter string
}
What I want is to get chapters of a book by using this command:book.chapters
.
I use the following codes to get books and chapters:
var book models.Book
db.First(&book, "id = ?", 4)
fmt.Println(book.ID, book.Chapters) // returns []
when I query chapters with book_id = 4, I get 11 results:
var chapters []models.Chapter
db.Find(&chapters, "book_id = ? ", 4)
fmt.Println("len(chapters) = ", len(chapters)) // len(chapters) =11
and when I set db.LogMode(true) and see what happens in the code I see that querying book
only queries the books not joining that with chapters
:
SELECT * FROM "book" WHERE (id = 4) ORDER BY "book"."id" ASC LIMIT 1
Is there something that I missed from the documentation? how should I make the book struct the get non-empty book.chapters
.