lunemec / go-clean-architecture

13 stars 1 forks source link

How to represent ForeignKey fields in gengeric model #3

Open lunemec opened 6 years ago

lunemec commented 6 years ago

Suppose you have MySQL model:

type Organization struct {
    ID         uint          `db:"id"`
    ParentID   sql.NullInt64 `db:"parent_id"`
    Name       string
    LocationID sql.NullInt64 `db:"location_id"`
}

which converts to "generic" app model:

type Organization struct {
    ID       uint
    Parent   *Organization
    Name     string
    Location *Location

    Contacts []Contact
}

Should generic app model have LocationID and ParentID fields? If so, why? Wouldn't this be better?

func doSomething() {
    org := Organization{} // Loaded data from MySQL
    if org.Location != nil {  // <-- this seems clearer to mean Location can be empty.
        locationID := org.Location.ID
    }
}

// VS
func doSomethingElse() {
    org := Organization{} // Loaded data from MySQL
    if org.LocationID != 0 {
        locationID := org.LocationID
    }
}
thfre commented 6 years ago

I don't think Generic model should have LocationID and ParentID. If the objects a nil then they have no relevance and if they are not, the objects themselves hold their keys.