代码之家  ›  专栏  ›  技术社区  ›  Nurzhan Nogerbek

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

  •  0
  • Nurzhan Nogerbek  · 技术社区  · 7 年前

    PostgreSQL语言

    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)
    );
    

    正如您所看到的,每个问题只有一个小部件类型的offerend答案。

    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"
    

    模型.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"
    }
    

    :

    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 回复  |  直到 7 年前