diff --git a/models/author.go b/models/author.go index ad961b6..e6086e7 100644 --- a/models/author.go +++ b/models/author.go @@ -39,6 +39,7 @@ func GetAuthorByID(id int64) (author Author, exists bool, err error) { // GetAuthorsByBook get all authors of a book func GetAuthorsByBook(bookID int64) (authors []Author, err error) { err = x. + Select("authors.*"). Table("authors_books"). Join("INNER", "authors", "authors_books.author_id = authors.id"). Where("book_id = ?", bookID). diff --git a/models/authors_add.go b/models/authors_add.go index 588b11b..7b7928e 100644 --- a/models/authors_add.go +++ b/models/authors_add.go @@ -9,7 +9,7 @@ func AddAuthor(author Author) (newAuthor Author, err error) { } // Get the newly inserted author - newAuthor, _, err = GetAuthorByID(author.ID) + newAuthor = author return newAuthor, err } diff --git a/models/books_add.go b/models/books_add_update.go similarity index 91% rename from models/books_add.go rename to models/books_add_update.go index f9937e3..59a8a8d 100644 --- a/models/books_add.go +++ b/models/books_add_update.go @@ -69,6 +69,9 @@ func AddOrUpdateBook(book Book) (newBook Book, err error) { return Book{}, err } + // Delete all (maybe) previously existing author relations + x.Delete(AuthorBook{BookID:book.ID}) + // Take the authors, look if they exist, if they don't create them authorBookRelation := make([]AuthorBook, 0) @@ -82,19 +85,16 @@ func AddOrUpdateBook(book Book) (newBook Book, err error) { if !exists { // We have to insert authors on this inperformant way, because we need the ne ids afterwards - authorToBeInserted := new(Author) - authorToBeInserted.Forename = author.Forename - authorToBeInserted.Lastname = author.Lastname - _, err := x.Insert(authorToBeInserted) + insertedAuthor, err := AddAuthor(author) if err != nil { return Book{}, err } - author.ID = authorToBeInserted.ID + author.ID = insertedAuthor.ID } - // Prepare new author Relateion + // Prepare new author Relation authorBookRelation = append(authorBookRelation, AuthorBook{BookID: book.ID, AuthorID: author.ID}) }