这里的 struct 中外键类型为何选择 string 而不是 int 呢?

主题模型 struct 结构

type Topic struct {
    models.BaseModel

    Title      string `gorm:"type:varchar(255);not null;index"`
    Body       string `gorm:"type:longtext;not null"`
    UserID     string `gorm:"type:bigint;not null;index"`
    CategoryID string `gorm:"type:bigint;not null;index"`

    // 会创建 user_id 和 category_id 外键的约束
    User     User
    Category Category

    models.CommonTimestampsField
}

这里的 UserIDCategoryID 为何选择 string 类型而不 int 类型呢?
是为了方便课程处理数据的缘故吗?

比如:后期增加了需求,topic 表需要增加一个审核用户ID字段,如:audit_user_id
如果想判断这条数据有没有被审核,则控制里面的代码:

topicModel := topic.Get(c.param("id"))
if topicModel.ID == 0 {
   response.Abort404(c)
   return
}
// 审核时检测该数据是否已被审核过
if topicModel.AuditUserID > 0 {
    //do something
}

此时,if topicModel.AuditUserID > 0这句代码就会报错 Invalid operation: topicModel.AuditUserID > 0 (mismatched types string and untyped int)
每次遇到这样的情况就需要将 string 类型的 AuditUserID 强转为 int 类型后再进行判断。

感觉这样不太优雅,有没有更好的方案呢~~

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!