I am having an issue with saving many2many
in gorm with go. The problem is that I want a book to have multiple genres, but when I try to use the Association method to add genres to the books, I get the following error
Error 1062: Duplicate entry '2debe760-2cf8-4dff-80dd-a912ff6f8176' for key 'book_id'
I do know that the SQL generated by the gorm is false which gives the error above. The question is what should I do to avoid the check for "where not exist"? That check is not needed at all for many to many relationship. I dont understand the purpose of the check.
INSERT INTO `book_genres` (`book_id`,`genre_id`) SELECT 'e038ba55-ecd9-41a3-a1ea-36da86d465ea','3df46a42-c1ce-416c-b246-753b81fc2246' FROM DUAL WHERE NOT EXISTS (SELECT * FROM `book_genres` WHERE `book_id` = 'e038ba55-ecd9-41a3-a1ea-36da86d465ea' AND `genre_id` = '3df46a42-c1ce-416c-b246-753b81fc2246')
This is my setup, what I am missing to ensure I don't get the error?
type Book struct {
Identifiable
Name string `sql:"type:varchar(255);not null" json:"name"`
Pages int `sql:"type:integer;not null"`
AuthorId uuid.UUID `sql:"type:varchar(36);foreign_key"`
Genres []Genre `gorm:"many2many:book_genres;"`
}
type Genre struct {
Identifiable
Name string `sql:"type:varchar(255);not null" json:"name"`
Books []*Book
}
var auth domain.Author;
auth.Age = 59;
auth.Name = "Fyodor Dostoyevsky";
fmt.Println(auth)
var drama domain.Genre
drama.Name = "Drama"
var thriller domain.Genre
thriller.Name = "Thriller"
var genres []domain.Genre
genres = append(genres, drama, thriller)
engine.Save(&drama)
engine.Save(&thriller)
var book1 domain.Book;
book1.Name = "Idiot";
book1.Pages = 11000;
book1.AuthorId = auth.Id;
var book2 domain.Book;
book2.Name = "Crime and Murder";
book2.Pages = 854;
book2.AuthorId = auth.Id;
engine.Save(&auth)
engine.Model(&auth).Association("Books").Append(&book2)
engine.Model(&auth).Association("Books").Append(&book1)
err := engine.Debug().Model(&book1).Association("Genres").Append([]domain.Genre{drama, thriller});
if err != nil {
fmt.Println(err)
}