I am trying to set foreign keys on the data models using gorm. The following code shows the models I am trying to use, and the table structure I am trying to create.
package main
import (
"log"
"database/sql/driver"
"encoding/json"
"errors"
"time"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
type JSONB map[string]interface{}
func (j JSONB) Value() (driver.Value, error) {
if j == nil {
return nil, nil
}
return json.Marshal(j)
}
func (j *JSONB) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
return errors.New("failed to unmarshal JSONB value")
}
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return err
}
*j, ok = v.(map[string]interface{})
if !ok {
return errors.New("failed to convert JSONB value")
}
return nil
}
type Tag struct {
Tag_id int `gorm:"primary_key;not null"`
Tag_name string `gorm:"type:varchar(255);not null"`
}
type User_Entity struct {
Id string `gorm:"type:varchar(36);not null;unique"`
Email string `gorm:"type:varchar(255);not null"`
}
type Log_Settings struct {
Log_Setting_Id int `gorm:"primary_key;not null"`
Log_Setting_Name string `gorm:"type:varchar(20);not null"`
Creator_Id string `gorm:"type:varchar(36);not null"`
User_Entity User_Entity `gorm:"foreignKey:Creator_Id"`
}
type Pass_Fail_Categories struct {
Category_Id int `gorm:"primary_key;unique;not null"`
Category_Name string `gorm:"type:varchar(15);not null"`
}
type Pass_Fail_Category_Messages struct {
Category_Id int `gorm:"not null"`
Messages string `gorm:"type:varchar(50);unique;not null"`
Pass_Fail_Categories Pass_Fail_Categories `gorm:"foreignKey:Category_Id"`
}
type Pass_Fail_Criteria_Feilds struct {
Criteria_Id int `gorm:"primary_key;not null"`
Category_Id int `gorm:"not null"`
Category_Message string `gorm:"type:varchar(50);not null"`
Numeric_Operator string `gorm:"type:varchar(2);not null"`
Criteria_Value int `gorm:"not null"`
Pass_Fail_Categories *Pass_Fail_Categories `gorm:"foreignKey:Category_Id"`
Pass_Fail_Category_Messages Pass_Fail_Category_Messages `gorm:"foreignKey:Category_Message;references:Messages"`
}
func main() {
db, err := gorm.Open(postgres.Open("host=localhost user=postgres password=1234567 dbname=tester port=5432 sslmode=disable"), &gorm.Config{})
if err != nil {
log.Println("connection failed")
}
db.AutoMigrate(&Tag{})
db.AutoMigrate(&User_Entity{})
db.AutoMigrate(&Pass_Fail_Categories{})
db.AutoMigrate(&Pass_Fail_Category_Messages{})
db.AutoMigrate(&Pass_Fail_Criteria_Feilds{})
}
I am auto migrating the models above, but I am having trouble setting the foreign keys. I am trying to create the following table structure:
CREATE TABLE Pass_Fail_Criteria_Feilds
(
Criteria_Id SERIAL PRIMARY KEY NOT NULL,
Category_Id INTEGER REFERENCES Pass_Fail_Categories(Category_Id) NOT NULL,
Category_Message VARCHAR(50) REFERENCES Pass_Fail_Category_Messages(Messages) NOT NULL,
Numeric_Operator VARCHAR(2) NOT NULL,
Criteria_Value INTEGER NOT NULL
);
How can I set foreign keys in my data models using gorm?