go-gorm/gorm.io

[Question] Belongs-To Association without a Foreign Key

KyleKotowick opened this issue · 1 comments

Document Link

https://gorm.io/docs/belongs_to.html

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?

Submitted in the wrong repository; I've re-submitted it in the correct one.