Twpeak_继续攀登 2022-07-07 21:11
浏览 9
已结题

GORM外键失效问题

问题遇到的现象和发生背景

GORM用tag设置外键时,发现数据库迁移后,外键并未创建

问题相关代码,请勿粘贴截图
type SysArticle struct {
    global.G_MODEL
    UserId            uint                    `json:"userId" gorm:"comment:发布用户ID;column:user_id"`
    Title            string                    `json:"title" gorm:"comment:文章标题;column:title"`
    ArticleContent    string                    `json:"articleContent" gorm:"comment:文章内容;column:article_content;type:varchar(2000)"`
    LikesNum        *int                    `json:"likesNum" gorm:"comment:点赞数;column:like_num;default:0 "`
    ReplyNum        *int                    `json:"replyNum" gorm:"comment:回复数;column:reply_num;default:0 "`
    SortId            uint                    `json:"sortId" gorm:"comment:分类Id;"`
    Comments         *[]SysComment             `json:"comments" gorm:"foreignKey:ArticleId;ASSOCIATION_FOREIGNKEY:ID"`
    Labels             []SysLabels                `json:"labels" gorm:"many2many:sys_article_labels"`
}
type SysComment struct {
    global.G_MODEL
    ArticleId            uint    `json:"articleId" gorm:"comment:所属文章ID;column:article_id"`
    UserId              uint    `json:"userId" gorm:"comment:发表评论用户ID;column:user_id"`
    CommentContent        string    `json:"commentContent" gorm:"comment:评论内容;column:comment_content;type:varchar(1000)"`
    ParentCommentId        uint    `json:"parentCommentId" gorm:"comment:父评论ID;column:parent_comment_id"`
    LikesNum            *int        `json:"likesNum" gorm:"comment:点赞数;column:like_num;default:0 "`
}
type SysLabels struct {
    Id                uint            `json:"labelId" gorm:"comment:标签id;"`
    LabelName        string        `json:"labelName" gorm:"comment:标签名称;column:label_name"`
    Article            []SysArticle `json:"article" gorm:"many2many:sys_article_labels"`
}
运行结果及报错内容

项目中代码关系比较多,这里仅贴了三个表,实际上所有的关系都按照要求。用tag设置,一对多,多对多。但只有多对多自动生成 了关系表,一对多的表没有外键生成。

我的解答思路和尝试过的方法

尝试设置了各种设置。

我想要达到的结果

知晓背后的原因,在不适用操作语句的情况下,仅使用tag设置生成外键

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 7月15日
    • 创建了问题 7月7日