如何在GORM中正确创建ForeignKey Golang应用程序?

时间:2019-03-04 10:58:26

标签: postgresql go go-gorm

PostgreSQL 数据库中,我有2个表:

CREATE TABLE WIDGET_TYPE(
    WIDGET_TYPE_ID SERIAL PRIMARY KEY NOT NULL,
    WIDGET_TYPE_NAME VARCHAR NOT NULL UNIQUE
);

CREATE TABLE QUESTION(
    QUESTION_ID SERIAL PRIMARY KEY NOT NULL,
    QUESTION_TEXT TEXT NOT NULL UNIQUE,
    WIDGET_TYPE_ID INT NOT NULL,
    FOREIGN KEY (WIDGET_TYPE_ID) REFERENCES WIDGET_TYPE (WIDGET_TYPE_ID)
);

如您所见,每个问题只有一个小部件类型用于要约答案。

在那一步之后,我试图在Golang应用程序中设计模型。我将GORM库用于此任务。尝试在question表中创建新条目时遇到问题。在POST请求的正文中,我发送JSON对象:

{
    "question_text": "NEW QUESTION TEXT HERE",
    "widget_type_id": 2
}

错误

pq: insert or update on table "question" violates foreign key constraint "question_widget_type_id_fkey"

models.go

package models

type WidgetType struct {
    WidgetTypeID   int    `gorm:"primary_key" json:"widget_type_id"`
    WidgetTypeName string `gorm:"not null;unique" json:"widget_type_name"`
}

func (WidgetType) TableName() string {
    return "widget_type"
}

type Question struct {
    QuestionID int `gorm:"primary_key" json:"question_id"`
    QuestionText string `gorm:"not null;unique" json:"question_text"`
    WidgetType WidgetType `gorm:"foreignkey:WidgetTypeID"`
    WidgetTypeID uint
}

func (Question) TableName() string {
    return "question"
}

handlers.go

var CreateQuestion = func(responseWriter http.ResponseWriter, request *http.Request) {
    question := models.Question{}
    decoder := json.NewDecoder(request.Body)
    if err := decoder.Decode(&question); err != nil {
        utils.ResponseWithError(responseWriter, http.StatusBadRequest, err.Error())
        return
    }
    defer request.Body.Close()
    if err := database.DBGORM.Save(&question).Error; err != nil {
        utils.ResponseWithError(responseWriter, http.StatusInternalServerError, err.Error())
        return
    }
    utils.ResponseWithSuccess(responseWriter, http.StatusCreated, "The new entry successfully created.")
}

我在哪里弄错了?

我添加了对GORM的内置记录器支持。在控制台中,它向我显示下一条SQL语句:

INSERT INTO "question" ("question_text","widget_type_id") VALUES ('NEW QUESTION TEXT HERE',0) RETURNING "question"."question_id"

您会看到widget_type_id的值为0。为什么?

0 个答案:

没有答案