Hello, I'm trying to map sql tables and relations to go structs. This is just for a simple side project to learn some go. I'm mapping tables directly to structs, but I'm not sure how to handle relations. I have thought of embedding struct on each side e.g.
type User struct {
ID int
*Organization
}
and
type Organization struct {
ID int
*User
}
Is this correct? or should i have another struct for each relation?
SQL would have user table, organization table and user_organization table for relation,
edit : assume its N to N identifying relation
Or am I completely off the track on this one? How would I create constructor for these?
评论:
motojo:
krzykizza:This should help - SQLX document to understand embedded structs: http://jmoiron.github.io/sqlx/#advancedScanning
As far as I know, you shouldn't build the relationships into the structs. Here is how I create them for MySQL:
// User table contains the information for each user type User struct { Id uint32 `db:"id"` First_name string `db:"first_name"` Last_name string `db:"last_name"` Email string `db:"email"` Password string `db:"password"` Status_id uint8 `db:"status_id"` Created_at time.Time `db:"created_at"` Updated_at time.Time `db:"updated_at"` Deleted uint8 `db:"deleted"` } // User_status table contains every possible user status (active/inactive) type User_status struct { Id uint8 `db:"id"` Status string `db:"status"` Created_at time.Time `db:"created_at"` Updated_at time.Time `db:"updated_at"` Deleted uint8 `db:"deleted"` }
thanks, it helped.
