0

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)
}
Heikkisorsa
  • 740
  • 9
  • 31
  • What is clause.Associations ? Can you show your model used in post ? – Eklavya Oct 13 '20 at 20:58
  • `clause.Associations` is from the GORM documentation (https://gorm.io/docs/preload.html#Preload-All) and is basically the expression `@@@as@@@` used for eager preload all associations (without one-to-many and many-to-many). The User model consists of regular fields like `Name` and `Age`, but also one-to-one associations like `Address` of type `Address`, which I want to eagerly preload and does not work. Including the one-to-one associations explicitly in `preload` works though. – Heikkisorsa Oct 14 '20 at 09:19

1 Answers1

0

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