登录
首页 >  Golang >  Go问答

GORM 无法正确处理一对多关系中的更新操作

来源:stackoverflow

时间:2024-02-29 13:00:24 231浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《GORM 无法正确处理一对多关系中的更新操作》,很明显是关于Golang的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

问题内容

我有两个表用户和文档。它们以这样一种方式相关:每个文档必须属于使用一对多关系的用户。当我尝试更新文档时出现以下错误

error: insert or update on table "documents" violates foreign key
constraint "fk_users_documents" (sqlstate 23503)

这是我的结构定义和更新函数

type User struct {
    gorm.Model
    Name      string
    Email     string
    Password  string
    Documents []Document 
}

type Document struct {
    gorm.Model
    Name   string
    UserID uint
}




//Update document by id
func (h handler)UpdateDocument(w http.ResponseWriter, r *http.Request) {

    // once again, we will need to parse the path parameters
    var updatedDoc Document
    reqBody, _ := ioutil.ReadAll(r.Body)
    json.Unmarshal(reqBody, &updatedDoc)
    var document Document
    vars := mux.Vars(r)
    id := vars["id"]


    
    
    if result := Db.First(&updatedDoc, id); result.Error != nil {
        fmt.Println(result.Error)
    }

    document.Name=updatedDoc.Name

    
    Db.Save(&document)
    json.NewEncoder(w).Encode(&updatedDoc)
}

正确答案


您正在调用 Db.Save(&document)document 仅填充了其 Name 字段。这意味着 UserID 设置为 0。我猜测 User 表中不存在任何 ID 为 0 的用户,因此这违反了外键约束。

更新文档时,UserID 字段应始终设置为现有用户,否则查询将失败。

不管怎样,我建议你学习一些数据库和golang基础知识,因为你发布的代码相当混乱。

好了,本文到此结束,带大家了解了《GORM 无法正确处理一对多关系中的更新操作》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>