lunemec/go-clean-architecture

How to represent ForeignKey fields in gengeric model

Opened this issue · 1 comments

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

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.