我遇到了将many2many
保存在gorm中的问题。问题是我想要一本书有多种类型,但是当我尝试使用Association方法为书籍添加类型时,
我收到以下错误
Error 1062: Duplicate entry '2debe760-2cf8-4dff-80dd-a912ff6f8176' for key 'book_id'
我知道gorm生成的SQL是false,它给出了上面的错误。问题是我应该怎么做以避免检查“哪里不存在”?对于多对多关系,根本不需要该检查。我不明白检查的目的。
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')
这是我的设置,我缺少什么以确保我没有收到错误?
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)
}