I am gettin this error when i try to automigrate my tables based on my structs i dont know why im gettin this error
failed to parse value &models.Model{ID:0x0, CreatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), UpdatedAt:time.Date(1, time.January, 1, 0, 0, 0, 0, time.UTC), DeletedAt:, DogData:[]models.DogData(nil)}, got error invalid field found for struct github.com/dog-page/models.Model's field DogData: define a valid foreign key for relations or implement the Valuer/Scanner interface
im new at golang languague and gorm specificly when it comes to create struct for raw json data here are my intention of a struct using gorm:
type Model struct {
ID uint `gorm:"primarykey:id" json:"id:_id"`
CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
UpdatedAt time.Time `gorm:"column:updated_at" json:"updated_at"`
DeletedAt *time.Time `gorm:"column:deleted_at" json:"deleted_at"`
DogData []DogData
}
type DogData struct {
DogDataID uint
Name string `json:"name"`
Life_Span string `json:"life_span"`
Temperaments string `json:"temperament"`
Weight datatypes.JSON `json:"weight"`
Height datatypes.JSON `json:"height"`
Image datatypes.JSON `json:"image"`
}
type Weight struct {
Imperial string `json:"imperial"`
Metric string `json:"metric"`
}
type Height struct {
Imperial string `json:"imperial"`
Metric string `json:"metric"`
}
type Image struct {
URL string `json:"url"`
}
Model's field DogData: define a valid foreign key for relations
Model has one-to-many relation to DogData, for which gorm is not able to identify the foreign key.
You need to specify the column that will store Model.ID
in DogData
(gorm looks for ModelID by default),
type Model struct {
ID uint `gorm:"primarykey:id" json:"id:_id"`
...
DogData []DogData
}
type DogData struct {
ModelID uint
DogDataID uint
...
}
//CREATE TABLE `dog_data` (`model_id` integer,`dog_data_id` integer,`name` text,`life_span` text,`temperaments` text,CONSTRAINT `fk_models_dog_data` FOREIGN KEY (`model_id`) REFERENCES `models`(`id`))
OR if you want to use another column than specify that with foreignKey tag
type Model struct {
ID uint `gorm:"primarykey:id" json:"id:_id"`
...
DogData []DogData `gorm:"foreignKey:DogDataID"`
}
type DogData struct {
DogDataID uint
...
}
//CREATE TABLE `dog_data` (`model_id` integer,`dog_data_id` integer,`name` text,`life_span` text,`temperaments` text,CONSTRAINT `fk_models_dog_data` FOREIGN KEY (`dog_data_id`) REFERENCES `models`(`id`))
Not sure about the use case but I think the DogData
can be simplified as, dropping Model
struct completely as it is same as gorm.Model
type DogData struct {
gorm.Model
Name string `json:"name"`
...
}