Moved getting authors from a book to a seperate function

+ Implemented getting quantity in book list
This commit is contained in:
konrad 2017-11-17 11:40:43 +01:00 committed by kolaente
parent a3b0d1d94b
commit 9016443409
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
3 changed files with 26 additions and 26 deletions

View File

@ -35,3 +35,18 @@ func GetAuthorByID(id int64) (author Author, exists bool, err error) {
return author, has, err return author, has, err
} }
// GetAuthorsByBook get all authors of a book
func GetAuthorsByBook(bookID int64) (authors []Author, err error) {
err = x.
Table("authors_books").
Join("INNER", "authors", "authors_books.author_id = authors.id").
Where("book_id = ?", bookID).
Find(&authors)
if err != nil {
return authors, err
}
return authors, err
}

View File

@ -74,27 +74,16 @@ func GetBookByID(ID int64) (book Book, exists bool, err error) {
} }
// Get publisher. We can't join it because xorm ignores the PublisherID option in struct // Get publisher. We can't join it because xorm ignores the PublisherID option in struct
publisher := Publisher{ID: book.Publisher} book.PublisherFull, _, err = GetPublisherByID(book.Publisher)
_, err = x.Get(&publisher)
if err != nil { if err != nil {
fmt.Println("Error getting publisher:", err) fmt.Println("Error getting publisher:", err)
} }
book.PublisherFull = publisher
// Get all authors // Get all authors
var authors []Author book.Authors, err = GetAuthorsByBook(book.ID)
err = x.
Table("authors_books").
Select("authors.*").
Join("INNER", "authors", "authors_books.author_id = authors.id").
Where("book_id = ?", book.ID).
Find(&authors)
if err != nil { if err != nil {
fmt.Println("Error getting authors:", err) fmt.Println("Error getting authors:", err)
} }
book.Authors = authors
} }
return book, has, err return book, has, err

View File

@ -25,30 +25,26 @@ func ListBooks(searchterm string) (books []*Book, err error) {
} }
} }
// Get all authors and publishers // Get all authors, publishers and quantities
for i, book := range books { for i, book := range books {
// Get quantities
books[i].Quantity, err = GetQuantityByBook(book.ID)
if err != nil {
fmt.Println("Error getting quantity:", err)
}
// Get publisher // Get publisher
publisher := Publisher{ID: book.Publisher} books[i].PublisherFull, _, err = GetPublisherByID(book.Publisher)
_, err := x.Get(&publisher)
if err != nil { if err != nil {
fmt.Println("Error getting publisher:", err) fmt.Println("Error getting publisher:", err)
} }
books[i].PublisherFull = publisher
// Get all authors // Get all authors
var authors []Author books[i].Authors, err = GetAuthorsByBook(book.ID)
err = x.
Table("authors_books").
Join("INNER", "authors", "authors_books.author_id = authors.id").
Where("book_id = ?", book.ID).
Find(&authors)
if err != nil { if err != nil {
fmt.Println("Error getting authors:", err) fmt.Println("Error getting authors:", err)
} }
books[i].Authors = authors
} }
return books, err return books, err