【问题标题】:Is it possible to get GORM to populate nil values with say an empty slice instead of being just nil?是否有可能让 GORM 用空切片而不是 nil 填充 nil 值?
【发布时间】:2015-12-13 01:07:38
【问题描述】:

我目前正在做一个项目,现在我有一些基本的 Javascript

blah.map(function(lBlah) {});

blah 由 ajax 请求生成到数据库,该数据库返回一个对象数组(或切片,如果您愿意)

唯一的问题是我收到一个 JS 错误:cannot read property 'map' of null 这是因为如果我的 one-to-many 关联当时没有关联值,它只会使该字段 nil 而不是空切片,所以当我 @ 987654326@ 它发送一个空值而不是一个空的[],这将修复我的所有错误,目前必须覆盖从数据库返回的每个struct 并检查 nil 值然后make([]blah, 0) 很烦人,看起来乱。有没有更简单的方法来实现这一点?是否可以设置默认 json:"default:[]" 或其他东西?

// ForumContainer is a table in the database
type ForumContainer struct {
    gorm.Model
    ContainerName string `sql:"not null;unique"`
    AccessLevel   int    `sql:"not null;default:0"`
    MainThreads   []ForumMainThreads
}

// ForumMainThreads is the table in the database
type ForumMainThreads struct {
    gorm.Model
    ForumContainerID int    `sql:"index"`
    ThreadName       string `sql:"not null;unique"`
    Threads          int    `sql:"not null;default:0"`
    Replies          int    `sql:"not null;default:0"`
    AccessLevel      int    `sql:"not null;default:0"`
    Posts            []ForumMainThreadsPosts
}

// ForumMainThreadsPosts is a table in the database
type ForumMainThreadsPosts struct {
    gorm.Model
    UserID             int    `sql:"index"`
    ForumMainThreadsID int    `sql:"index"`
    Title              string `sql:"not null;unique"`
    Body               string `sql:"type:text;not null"`
    Sticky             bool   `sql:"not null;default:0"`
    Views              int    `sql:"not null;default:0"`
    ReplyCount         int    `sql:"not null;default:0"`
    Replies            []ForumMainPostsReplies
}

// ForumMainPostsReplies is a table in the database
type ForumMainPostsReplies struct {
    gorm.Model
    ForumMainThreadsPostsID int `sql:"index"`
    UserID                  int `sql:"index"`
    Body                    string
}

查询是通过以下方式完成的:

db.Preload("MainThreads").Find(&forumContainers)

【问题讨论】:

  • 您能补充更多信息吗?你是如何定义模型的?你怎么查询的?
  • @AbelardoMendoza 更新
  • 好吧,我有一个类似的模式,具有一对多关系,并且切片作为空切片出现,并且作为空数组正确传递到前端。你可以试试:fmt.Println(forumContainers.MainThreads) 在查询 db.Preload("MainThreads").Find(&forumContainers) 被执行之后。它也可能是 GORM 的旧版本。你用的是哪个版本?
  • @AbelardoMendoza 据我所知我正在使用,最近几个小时前我刚刚做了一个go get
  • 我刚刚更新了我的 gorm 并尝试了相同的一对多模型,但我仍然得到了空切片。您是否在查询后立即尝试了 fmt.Println?

标签: javascript go go-gorm


【解决方案1】:

您可以修改整个列表以检查您的归档是否为 nil,然后将其替换为您的结构的空切片,如下所示:

for i := range list {
    if list[i].MainThreads== nil {
        list[i].SubCategories = make([]ForumMainThreads, 0)
    }
}

并对任何类型的切片的所有字段重复此操作

【讨论】:

猜你喜欢
  • 2016-03-22
  • 1970-01-01
  • 2017-11-02
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 1970-01-01
  • 2020-11-06
  • 1970-01-01
相关资源
最近更新 更多