I just started learning GORM and currently trying to fetch data from one to many tables. I have two tables :users and documents. A user can have multiple documents . When i try fetching documents I keep getting the error
documents: unsupported relations for schema User
SELECT * FROM "users" WHERE "users"."deleted_at" IS NULL
Below is the code where I attempt to fetch data
type User struct {
gorm.Model
Name string
Email string
Password string
Documents []Document
}
type Document struct {
gorm.Model
Name string
DateCreated string
UserID uint
}
Function to fetch data
func GetAll(db *gorm.DB) ([]models.User, error) {
var users []models.User
// err := db.Model(&models.User{}).Preload("documents").Find(&users).Error
err:=db.Preload("documents").Find(&[]models.User{}).Error
fmt.Println(err)
fmt.Println("got users")
return users, err
}
What am I doing wrong here?
CodePudding user response:
db.Preload("documents")
should be db.Preload("Documents")
same as name of the field Documents
in User
struct
CodePudding user response:
It looks like you are trying to access the relationship between the User and Document models incorrectly. When defining a relationship in GORM, you need to specify the foreign key in the child model (in this case, the Document model) and the association field in the parent model (in this case, the User model).
It should look something like:
type User struct {
gorm.Model
Name string
Email string
Password string
// Define the association field for the documents relationship
Documents []Document gorm:"foreignkey:UserID"
}
type Document struct {
gorm.Model
Name string
DateCreated string
// Define the foreign key for the documents relationship
UserID uint
}
With this change, you should be able to use the Preload
method to fetch the related Document
records for each User
record.
func GetAll(db *gorm.DB) ([]models.User, error) {
var users []models.User
err := db.Preload("Documents").Find(&users).Error
fmt.Println(err)
fmt.Println("got users")
return users, err
}