Library/models/book.go

56 lines
1.3 KiB
Go

package models
import "fmt"
// Book holds a book
type Book struct {
ID int64 `xorm:"int(11) autoincr not null unique pk"`
Title string `xorm:"varchar(250) not null"`
Isbn string `xorm:"varchar(30)"`
Year int64 `xorm:"int(11)"`
Price float64 `xorm:"double"`
Status int64 `xorm:"int(11)"`
Publisher int64 `xorm:"int(11)"`
Created int64 `xorm:"created"`
Updated int64 `xorm:"updated"`
PublisherFull Publisher `xorm:"-"`
Authors []Author `xorm:"-"`
}
// TableName returns the name for the books table
func (Book) TableName() string {
return "books"
}
// GetBookByID gets a Book by its ID
func GetBookByID(ID int64) (book Book, exists bool, err error) {
// Get the Book
has, err := x.ID(ID).Get(&book)
// Get publisher
publisher := Publisher{ID: book.Publisher}
_, err = x.Get(&publisher)
if err != nil {
fmt.Println("Error getting publisher:", err)
}
book.PublisherFull = publisher
// Get all authors
var authors []Author
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 {
fmt.Println("Error getting authors:", err)
}
book.Authors = authors
return book, has, err
}