Skip to content

Instantly share code, notes, and snippets.

@shtrih
Last active October 21, 2022 03:00
Show Gist options
  • Save shtrih/e3c4100faf699eb3e7dac3cc7f115496 to your computer and use it in GitHub Desktop.
Save shtrih/e3c4100faf699eb3e7dac3cc7f115496 to your computer and use it in GitHub Desktop.
Gorm.io preload by multiple foreign keys
type TimersTotal struct {
	UserID           string  `gorm:"column:user_id;" json:"-"`
	BookkeeperTeamID string  `gorm:"column:bookkeeper_team_id;" json:"-"`
	TeamID           *string `gorm:"column:team_id;" json:"-"`
	TaskID           *int64  `gorm:"column:task_id;" json:"-"`
	TypicalTaskID    *int64  `gorm:"column:typical_task_id;" json:"-"`
	TotalTimeSec     int64   `gorm:"column:total_time_sec;" json:"total_time_sec"`
	TotalTime        string  `gorm:"-" json:"total_time"`
}

// use TaskID or TypicalTaskID at a time but not both
type Timer struct {
	ID               string `gorm:"primary_key;column:id;default:uuid_generate_v3()" json:"id"`
	BookkeeperTeamID string `gorm:"column:bookkeeper_team_id;type:VARCHAR;size:26;" json:"bookkeeper_team_id"`
	TeamID           string `gorm:"column:team_id;type:VARCHAR;size:26;" json:"team_id"`
	UserID           string `gorm:"column:user_id;type:VARCHAR;size:26;" json:"-"`
	TaskID           *int64 `gorm:"column:task_id;type:INT8;" json:"task_id,omitempty"`
	TypicalTaskID    *int64 `gorm:"column:typical_task_id;type:INT8;" json:"typical_task_id,omitempty"`
  	// ...
  	
	// SELECT * FROM "timers_totals" WHERE "timers_totals"."task_id" = 42
	Total       *TimersTotal      `gorm:"foreignKey:TaskID;references:TaskID" json:"total,omitempty"`
  	// SELECT * FROM "timers_totals" WHERE ("timers_totals"."typical_task_id","timers_totals"."bookkeeper_team_id","timers_totals"."user_id","timers_totals"."team_id") IN ((112,'s57ngkgcqjfstbb8ef6dwnhm8c','6odn6h1n7iyk7ftuc8w85ugt4r','nj6x4zj1jtymdfdpe3jwimbgyh'))
	TypicalTotal *TimersTotal `gorm:"foreignKey:TypicalTaskID,BookkeeperTeamID,UserID,TeamID;references:TypicalTaskID,BookkeeperTeamID,UserID,TeamID" json:"typical_total,omitempty"`
}
	err = db.DB.Order("time_start").
		Preload("Total").
		Preload("TypicalTotal").
		Find(&result, "user_id = ?", userID).
		Error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment