【发布时间】: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 的事情
帮助表示赞赏。
【问题讨论】: