Skip to content

Joining children records as a slice #187

Description

@KennFatt

hello, i want to join my tables (one-to-many relation) and map them as a slice in the parent field.

here is my structs:

type User struct {
	ID          uint64     `db:"id" fieldopt:"omitempty"`
	CreatedAt   time.Time  `db:"created_at" fieldopt:"omitempty"`
	UpdatedAt   time.Time  `db:"updated_at" fieldopt:"omitempty"`
	DeletedAt   *time.Time `db:"deleted_at" fieldopt:"omitempty"`
	Versions    uint64     `db:"versions" fieldopt:"omitempty"`
	FirstName   string     `db:"first_name"`
	LastName    *string    `db:"last_name" fieldopt:"omitempty"`
	Email       string     `db:"email"`
	PhoneNumber *string    `db:"phone_number" fieldopt:"omitempty"`
	Password    string     `db:"password"`

	Expenses []*Expense `db:"expenses" fieldopt:"omitempty" fieldtag:"fk"`
}

var UserStruct = sqlbuilder.NewStruct(new(User))

type Expense struct {
	ID        uint64     `db:"id" fieldopt:"omitempty"`
	CreatedAt time.Time  `db:"created_at" fieldopt:"omitempty"`
	UpdatedAt time.Time  `db:"updated_at" fieldopt:"omitempty"`
	DeletedAt *time.Time `db:"deleted_at" fieldopt:"omitempty"`
	Versions  uint64     `db:"versions" fieldopt:"omitempty"`

	CreatedBy uint64 `db:"created_by"`
	UpdatedBy uint64 `db:"updated_by"`

	UserID    uint64    `db:"user_id"`
	Name      string    `db:"name"`
	Detail    *string   `db:"detail" fieldopt:"omitempty"`
	Amount    float64   `db:"amount"` // TODO: change it to decimal
	EventDate time.Time `db:"event_date"`
}

var ExpenseStruct = sqlbuilder.NewStruct(new(Expense))

Is it possible to query the users table and join the expenses together then map them as []*Expense slice in the User struct?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions