Using a custom DbAuthoring
model I add fields createdBy
to my database models. This works fine (I have to populate them manually fetching the user ID out of the JWT claim though).
Of course, the IDs in these fields refer to the user
table. But I want to treat them as strings for most cases, so I don’t have a “strong” relation set up. But I tried to add a custom relation:
This looks like:
// I am using a custom metadata model instead of gorm.model as I use UUID of type string as ID
type DbMetaData struct {
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
}
type DbAuthorData struct {
CreatedBy string `json:"createdBy"`
CreatedByUser *DbUser `gorm:"foreignKey:CreatedBy"` // I need to use a pointer here, as I do not want this field to be filled out by default, and I will get invalid "Invalid recursive type 'DbUser' DbUser → DbAuthorData → DbUser", as DbUser does have the same fields
}
type MyModel struct {
DbAuthorData
DbMetaData
ID string `gorm:"primaryKey"`
}
The foreign key is created correctly.
How do I select the data with a filled CreatedBy
correctly?
This works as expected, created_by
is filled, CreatedByUser
is nil
:
var myModels []MyModel
db.Find(&myModels)
How to I join and query these tables with GORM, so that CreatedByUser
is filled with data? Is this even possible automatically?
Preload
does not work (invalid relation), as I am using a pointer, Join
ing or using a custom query is returning the correct data, but not filling CreatedByUser
.