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

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?

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
}