diff --git a/models/author.go b/models/author.go index 1df3ff9..f42d6b5 100644 --- a/models/author.go +++ b/models/author.go @@ -1,7 +1,7 @@ package models type Author struct { - ID int64 `xorm:"int(11) autoincr not null unique pk"` + ID int64 `xorm:"int(11) autoincr not null unique pk"` Forename string `xorm:"varchar(250)"` Lastame string `xorm:"varchar(250) not null"` Created int64 `xorm:"created"` @@ -10,4 +10,17 @@ type Author struct { func (Author) TableName() string { return "authors" +} + +type AuthorBook struct { + ID int64 `xorm:"int(11) autoincr not null unique pk"` + AuthorID int64 `xorm:"int(11)"` + BookID int64 `xorm:"int(11)"` + + Created int64 `xorm:"created"` + Updated int64 `xorm:"updated"` +} + +func (AuthorBook) TableName() string { + return "authors_books" } \ No newline at end of file diff --git a/models/book.go b/models/book.go index b6b1a5f..efd33c6 100644 --- a/models/book.go +++ b/models/book.go @@ -10,6 +10,9 @@ type Book struct { Publisher int64 `xorm:"int(11)"` Created int64 `xorm:"created"` Updated int64 `xorm:"updated"` + + PublisherFull Publisher `xorm:"-"` + Authors []Author `xorm:"-"` } func (Book) TableName() string{ diff --git a/models/books_list.go b/models/books_list.go index 4a06230..59611c4 100644 --- a/models/books_list.go +++ b/models/books_list.go @@ -9,5 +9,31 @@ func ListBooks() (books []*Book, err error) { fmt.Println("Error getting Books", err) } + // Get all authors and publishers + for i, book := range books { + + // Get publisher + publisher := Publisher{ID: book.Publisher} + _, err := x.Get(&publisher) + if err != nil { + fmt.Println("Error getting publisher:", err) + } + books[i].PublisherFull = publisher + + // Get all authors + var authors []Author + err = x. + Table("authors_books"). + Join("INNER", "authors", "authors_books.author_id = authors.id"). + Where("book_id = ?", book.ID). + Find(&authors) + + if err != nil { + fmt.Println("Error getting authors:", err) + } + + books[i].Authors = authors + } + return books, err } diff --git a/models/models.go b/models/models.go index 56d1795..8a0dcaa 100644 --- a/models/models.go +++ b/models/models.go @@ -31,6 +31,7 @@ func SetEngine() (err error) { x.Sync(&User{}) x.Sync(&Publisher{}) x.Sync(&Author{}) + x.Sync(&AuthorBook{}) x.ShowSQL(true) return nil