Library/models/books_list.go

52 lines
1.2 KiB
Go

package models
import "fmt"
// BookPublisher struct to join books with publishers
type BookPublisher struct {
Book `xorm:"extends"`
Publisher `xorm:"extends"`
}
// ListBooks returns a list with all books, filtered by an optional searchstring
func ListBooks(searchterm string) (books []*Book, err error) {
if searchterm == "" {
err = x.Table("books").
//Join("INNER", "publishers", "books.publisher = publishers.id").
Find(&books)
if err != nil {
fmt.Println("Error getting Books", err)
}
} else {
err = x.Where("title LIKE ?", "%"+searchterm+"%").Find(&books)
if err != nil {
fmt.Println("Error getting Books", err)
}
}
// Get all authors, publishers and quantities
for i, book := range books {
// Get quantities
books[i].Quantity, err = book.getQuantity()
if err != nil {
fmt.Println("Error getting quantity:", err)
}
// Get publisher
books[i].Publisher, _, err = GetPublisherByID(book.PublisherID)
if err != nil {
fmt.Println("Error getting publisher:", err)
}
// Get all authors
books[i].Authors, err = GetAuthorsByBook(*book)
if err != nil {
fmt.Println("Error getting authors:", err)
}
}
return books, err
}