Invalid field found for struct .User's field: define a valid foreign key for relations or implement the Valuer/Scanner interface

Viewed 229

Problem:

I am testing: https://gorm.io/docs/has_many.html

import (
    "gorm.io/gorm"
)

// User has many CreditCards, UserID is the foreign key
type User struct {
  gorm.Model
  CreditCards []CreditCard
}

type CreditCard struct {
  gorm.Model
  Number string
  UserID uint
}

When I run it, I get:

[Error] invalid field found for struct test/models.User's field CreditCards: define a valid foreign key for relations or implement the Valuer/Scanner interface

If I add: UserID uint json:"user_id" in CreditCart structure it works fine:

type User struct {
  gorm.Model
  CreditCards []CreditCard 
}

type CreditCard struct {
  gorm.Model
  UserID uint `json:"user_id"`
  Number    string
  UserRefer uint
}

Is there something wrong in the documentation or in my code?

0 Answers
Related