英文:
Embedding model structs with same attribute names in golang
问题
使用go 1.5
和gorm
。
假设我想创建一个名为events
的表,其中包含created_by_id
和updated_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_id
和updated_by_id
的值。我需要怎么做才能确保CreatedBy
和UpdatedBy
的ByID
属性的列名不同呢?
英文:
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
问题在于你将CreatedBy
和UpdatedBy
都嵌入到了Event
结构体中,所以对Event.By
的调用是模棱两可的,不被允许的(你必须能够明确指定Event.CreatedBy.By
和Event.UpdatedBy.By
来消除这两个字段的歧义)。
解决方案很可能是_不要嵌入_这些类型,而是创建一个具有明确字段的结构体:
type Event struct {
CreatedBy CreatedBy
UpdatedBy UpdatedBy
}
gorm
现在应该知道如何消除这两个列的歧义。
当然,如果你只是为了列映射的目的将By
嵌入到CreatedBy
和UpdatedBy
中,那么你不需要声明新的结构体:
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 struct
s:
type By struct {
ByID sql.NullInt64
By *User
}
type Event struct {
CreatedBy By
UpdatedBy By
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论