在golang中嵌入具有相同属性名称的模型结构体

huangapple go评论85阅读模式
英文:

Embedding model structs with same attribute names in golang

问题

使用go 1.5gorm

假设我想创建一个名为events的表,其中包含created_by_idupdated_by_id两列。

我可以这样定义我的模型:

type By struct {
    ByID sql.NullInt64
    By *User
}

type CreatedBy struct {
    By
}

type UpdatedBy struct {
    By
}

type Event struct {
    CreatedBy
    UpdatedBy
}

当我尝试保存一个event对象时,by_id列的值将被保存,而不是created_by_idupdated_by_id的值。我需要怎么做才能确保CreatedByUpdatedByByID属性的列名不同呢?

英文:

Using go 1.5, and gorm.

Say I want to make an events table that has a created_by_id and an updated_by_id columns.

I write my models like

type By struct {
    ByID sql.NullInt64
    By *User
}

type CreatedBy struct {
    By
}

type UpdatedBy struct {
    By
}

type Event struct {
    CreatedBy
    UpdatedBy
}

When I try to save an event object, the value for the column by_id will try to be saved rather than the values for created_by_id and updated_by_id. What do I need to do to make sure the column names of ByID attribute are different for CreatedBy and UpdatedBy?

答案1

得分: 1

问题在于你将CreatedByUpdatedBy都嵌入到了Event结构体中,所以对Event.By的调用是模棱两可的,不被允许的(你必须能够明确指定Event.CreatedBy.ByEvent.UpdatedBy.By来消除这两个字段的歧义)。

解决方案很可能是_不要嵌入_这些类型,而是创建一个具有明确字段的结构体:

type Event struct {
    CreatedBy CreatedBy
    UpdatedBy UpdatedBy
}

gorm现在应该知道如何消除这两个列的歧义。

当然,如果你只是为了列映射的目的将By嵌入到CreatedByUpdatedBy中,那么你不需要声明新的结构体:

type By struct {
    ByID sql.NullInt64
    By *User
}

type Event struct {
    CreatedBy By
    UpdatedBy By
}
英文:

The problem is that you're embedding both CreatedBy and UpdatedBy into Event, so calls to Event.By are ambiguous and not allowed (you'd have to be able to specify Event.CreatedBy.By and Event.UpdatedBy.By explicitly to disambiguate the two fields).

The solution, most likely, would be to not embed the types, but actually create a struct with explicit fields:

type Event struct {
    CreatedBy CreatedBy
    UpdatedBy UpdatedBy
}

gorm should now know how to disambiguate the two columns.

Of course if you're only going to embed By into CreatedBy and UpdatedBy for the purposes of column mapping then you shouldn't need to declare new structs:

type By struct {
    ByID sql.NullInt64
    By *User
}

type Event struct {
    CreatedBy By
    UpdatedBy By
}

huangapple
  • 本文由 发表于 2015年12月25日 18:41:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/34462118.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定