'Gorm Preload convert key reference to string/integer
I am using Gorm and DB driver PostgreSQL and i have struct like this :
Projects
type Project struct {
ID int
ListingOrigin *ListingOrigin `gorm:"foreignkey:ListingID"`
}
func (Project) TableName() string {
return "project.projects"
}
ListingOrigin
type ListingOrigin struct {
ID int
ListingID string `gorm:"not null"`
OriginID uint `gorm:"not null"`
Project *Project `gorm:"foreignKey:ListingID;references:id"`
}
func (l *ListingOrigin) TableName() string {
return "listing_origins"
}
As u can see we can do Preload using ID on table Project, but first, I need to convert that value to string or integer.
When I do like this :
func (r *ProjectRepository) Options() (result []model.Project, err error) {
var projects []model.Project
query := r.db.Model(projects).Preload("ListingOrigin")
query.Order("name asc")
err = query.Find(&projects).Error
if err != nil {
return nil, err
}
return projects, nil
}
the error occurred :
ERROR: operator does not exist: character varying = integer (SQLSTATE 42883) [rows:0] SELECT * FROM "listing_origins" WHERE "listing_origins"."listing_id" IN (1,3,4) AND "listing_origins"."deleted_at" IS NULL
Is there any way to do this ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
