【问题标题】:How to insert rows with foreign keys using GORM?如何使用 GORM 插入带有外键的行?
【发布时间】:2021-05-30 16:12:08
【问题描述】:

定义模型

package models

import (
    "time"

    _ "gorm.io/gorm"
)



type User struct {
    UserID    uint   `gorm:"primarykey " json:"user_id"`
    Username  string `gorm:"unique" json:"username "` // gorm:"unique" makes it so that you can't have the same username twice
    CreatedAt time.Time
    Articles  []Article `gorm:"foreignKey:ArticleID"`
}

type Article struct {
    ArticleID    uint   `gorm:"primarykey " json:"article_id"`
    User         User   `gorm:"constraint:OnUpdate:CASCADE,OnDelete:SET NULL; foreignkey:UserID; association_foreignkey:UserID"`
    ArticleTitle string `json:"article_title"`
    ArticleBody  string `json:"article_body"`
    CreatedAt    time.Time
}

用于插入单个新文章的定义视图

package views

import (
    "fiber_server/database"
    "fiber_server/models"

    "github.com/gofiber/fiber/v2"
)

type User models.User
type Article models.Article

func CreateTestingArticles(c *fiber.Ctx) error {
    db, err := database.GetDBConn()
    if err != nil {
        panic(err)
    }

    db.Create(&User{
        UserID:   1,
        Articles: Article{ArticleTitle: "my_first_article", ArticleBody: "body"},
    })

    return c.SendString("articles created!")

}

view的东西抛出错误,说我cannot use (Article literal) (value of type Article) as []models.Article value in struct literal

在这种情况下,如何插入具有外键关系的新行到 User 模型? 我需要使用 User 模型来创建文章,还是只使用 Article 模型更好? 谈论改变 db.Create(&User 的事情

帮助表示赞赏。

【问题讨论】:

    标签: go go-gorm


    【解决方案1】:

    你只需要改变

        db.Create(&model.User{
            UserID: 1,
            Articles: []model.Article{
                {ArticleTitle: "my_first_article", ArticleBody: "body"},
            },
        })
    

    不要使用新类型UserArticle代替model.Usermodel.Articlesee example,另请阅读Specification

    插入行怎么样,我不使用gorm,但我想this 会有所帮助。 也许它应该是这样的:

    db.Model(&model.User{UserID: 1}).Association("Articles").Append(&model.Article{ArticleTitle: "my_first_article", ArticleBody: "body"})
    

    【讨论】:

    • 感谢您的回复!奇怪,有些事情不太奏效。测试并将处理程序更改为两个建议。 func CreateArticle(c *fiber.Ctx) error { db, err := database.GetDBConn() if err != nil { panic(err) } db.Create(&models.User{ UserID: 1, Username: "bob", Articles: []models.Article{ {ArticleTitle: "test-test-test", ArticleBody: "test-test-test"}, }, }) return c.SendString("article for userId 1 created!") } 没用。最后一个也不行。一旦我弄清楚这件事,就会发布一个已解决的案例。
    • 尝试将gorm.Model 嵌入到您的模型中。 type User struct { gorm.Model ... }
    • 创建了指向该事物的链接。 play.golang.org/p/e4pnlMn2KS-
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-30
    • 1970-01-01
    • 2021-06-03
    • 2021-07-07
    相关资源
    最近更新 更多