Unable to preload clause.Associations

982 Views Asked by At

I am using GORM in combination with Fiber. When querying all users with preloaded clause.Associations I get the following error:

can't preload field @@@as@@@ for entities.User

What does that mean? Without the preload of clause.Associations it works normally and but it does not show one-to-one associations.

func UsersGetAll(c *fiber.Ctx) error {
    db := database.DBConn
    users := []entities.User{}
    records := db.Preload(clause.Associations).Find(&users)
    if records.Error != nil {
        log.Println(records.Error)
        return c.Status(500).SendString(records.Error.Error())
    }

    return c.JSON(records.Value)
}
1

There are 1 best solutions below

0
On

Well looks like a problem with gorm tags: I will suppose the struct is something like this :

type Address struct {
ID int `gorm:"column:id;primaryKey"`
}
type User struct {
Name string `gorm:"column:name"`
Age string `gorm:"column:age"`
Address Address `gorm:"references:ID"`
}

And the code:

user:=User{}
if err:=db.Preload("Address").Find(&user).Error {
panic(err)
}

I think you also should look at this: Gorm relationship error: need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface