Gorm-与匿名字段有一种关系 [英] Gorm - Has One relation with anonymous field

查看:51
本文介绍了Gorm-与匿名字段有一种关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I use Golang and GORM. I have a User structure which has one Association.

type User struct {
    ID       int
    ...
}

type Association struct {
    ID       int
    UserID   int
}

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

I also have an AssoUser structure, which is composed of a anonymous field User, and has a pointer to 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)

我希望它可以创建 User Association ,但是只能创建User.

I expect it to create the User AND the Association, but it only creates the User.

我在做什么错?

推荐答案

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

I was having a similar issue, but I discovered it was an issue with anonymous types.

如果有

type Thing struct {
    Identifier string
    ext
}

type ext struct {
    ExtValue string
}

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

gorm won't be able to find ext, so it won't appear in the table at all.

但是,如果您有

type Thing struct {
    Identifier string
    Ext
}

type Ext struct {
    ExtValue string
}

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

ExtValue will appear in the table as a normal string, as if it were a part of the Thing object.

如果要建立一对一关系,则必须在结构中包含一个id.因此,上面的示例将如下所示:

If you want to make a has-one relationship, you have to include an id in your struct. So the above example would look like this:

type Thing struct {
    Identifier string
    Ext
}

type Ext struct {
    ThingId  uint
    ExtValue string
}

这篇关于Gorm-与匿名字段有一种关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆