Your Question
Hi,
I am using the FirstOrCreate function.
Suppose I have these trow structs and the corresponding tables:
type Book struct {
ID uint32
year uint32
Shelf Shelf `gorm:"foreignkey:ShelfID;references:ID"`
ShelfID uint32
}
type Shelf struct {
ID uint32
Name uint32
}
If I create a Book{year: 2023, shelf:{ID: 1, Name: Hello}} with FirstOrCreate and then create a second book which has the same fields but the Shelf differs: Book{year: 2023, shelf:{ID: 2, Name: Bye}} the second book will not be created and the ID of the first book will be returned. I assume that the ShelfID will be automatically deducted and then the uniqueness will be validated.
Is this behaviour intended? Do I always need to explicitly use the ShelfID AND the shelf to store a book?
The document you expected this should be explained
I assumed that providing the complete Shelf would be sufficient to check the uniqueness of both books.
Expected answer
Is this behaviour intended? Do I always provide the ShelfID in combination with the Shelf itself?
Comment From: saeidee
You should provide ShelfID, not the relation itself.