Your Question
I have a model (e.g. User) with a belongs-to association to another model (e.g. FavoriteBook). A User has a FavoriteBook, which is a string value that is the title of the book (technically, the User belongs to that Book). Book is a separate model with the title as primary key. The list of books we know about (Books in the database) may or may not include a user's FavoriteBook.
I'm trying to find a way to allow Gorm to preload a User's FavoriteBook, if it exists in the database, and to leave it as nil if it does not exist. My models might look like so:
type User struct {
gorm.Model
Name string
FavoriteBookId string
FavoriteBook *Book
}
type Book struct {
Title string `gorm:"primaryKey;"`
Author string
}
The problem is that with this, Gorm will create a foreign key constraint in the database for FavoriteBookId, which means that I can now no longer insert a User who has a FavoriteBook that isn't already in the database.
If I remove the FavoriteBook *Book field, then I can't pre-load the favorite book if it exists.
Is there a way to tell Gorm to preload the FavoriteBook object for the User if the Book exists in the database, without adding a foreign key constraint?
The document you expected this should be explained
https://gorm.io/docs/belongs_to.html
Expected answer
A way to preload associated models if the referenced primary key exists in the referenced table, without enforcing a foreign key constraint in the database.
Comment From: a631807682
https://gorm.io/docs/gorm_config.html#DisableForeignKeyConstraintWhenMigrating
Comment From: KyleKotowick
@a631807682 DisableForeignKeyConstraintWhenMigrating will disable foreign keys for all relations of all models in the migration.
If I have multiple relations in a single model, one of which I want to have a foreign key and one I do not, how would I achieve that?
Comment From: a631807682
@KyleKotowick use Session
https://github.com/go-gorm/gorm/pull/5885/files#diff-679ec3b5f6713c742552fbb893f8da549270441c34958ad09dc6ce4d6e02f184R239
Comment From: a631807682
If I have multiple relations in a single model
Sorry, we don't support it yet.