lemew123123
lemew123123

Reputation: 1

How to insert rows with foreign keys using GORM?

Defined models

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
}

Defined view to insert a single new Article

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!")

}

The view thing throws an error, saying that i cannot use (Article literal) (value of type Article) as []models.Article value in struct literal

How can i insert a new row with a foreign key relationship to the User model in this case? And do i need to use the User model to create the article, or is it better to do it by using only the Article model? talking about changing the db.Create(&User thing

Help appreciated.

Upvotes: 0

Views: 1800

Answers (1)

Maxim Eryomenko
Maxim Eryomenko

Reputation: 61

You just need change to

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

And don't use new types User and Article instead of model.User and model.Article, see example, also read Specification

What about insert row, I don't work with gorm, but i guess this will help. Maybe it should look like this:

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

Upvotes: 1

Related Questions