首页 文章

Gorm - 与匿名字段有一个关系

提问于
浏览
1

我使用Golang和GORM . 我有一个 User 结构,其中有一个 Association .

type User struct {
    ID       int
    ...
}

type Association struct {
    ID       int
    UserID   int
}

我还有一个 AssoUser 结构,它由一个匿名字段 User 组成,并有一个指向 Assocation 的指针 .

type AssoUser struct {
    User
    Asso *Association
}

我跑的时候

var assoUser AssoUser
assoUser.Asso = &Association{
   Name : "asso_name",
   ...
}
assoUser.Name = "user_name"
...

// filling the struct
db.Debug().Create(&assoUser)

我希望它创建 UserAssociation ,但它只创建用户 .

我究竟做错了什么 ?

1 回答

  • 0

    我遇到了类似的问题,但我发现这是一个匿名类型的问题 .

    如果你有

    type Thing struct {
        Identifier string
        ext
    }
    
    type ext struct {
        ExtValue string
    }
    

    gorm将无法找到 ext ,因此它根本不会出现在表格中 .

    但是,如果你有

    type Thing struct {
        Identifier string
        Ext
    }
    
    type Ext struct {
        ExtValue string
    }
    

    ExtValue 将作为普通字符串出现在表中,就好像它是 Thing 对象的一部分一样 .

    如果要 Build 一个一对一的关系,则必须在结构中包含一个id . 所以上面的例子看起来像这样:

    type Thing struct {
        Identifier string
        Ext
    }
    
    type Ext struct {
        ThingId  uint
        ExtValue string
    }
    

相关问题