Skip to content

Deferred eager loading of relations #1328

@yoh

Description

@yoh

Hi,
Is there a way to load (preload / eager load) relations after the initial query?

My use case is the following:

  1. I first fetch some records from the database.
  2. I run some business logic on them.
  3. Then, based on the result of that logic, I would like to load relations conditionally.

So the relations are not known at query time, but only after I’ve processed the main dataset.

I’m using the dvdrental sample database for my tests.
https://neon.com/postgresql/postgresql-getting-started/postgresql-sample-database

Thanks!

// first I load customers from db
ctx := c.Request().Context()
var customers []models.Customer
err := db.NewSelect().
	Model(&customers).
	Where("customer_id > ?", 10).
	// Relation("Address.City.Country"). // preload with JOIN
	// Relation("Payments.Rental"). // preload with WHERE IN
	OrderBy("customer_id", bun.OrderAsc).
	Limit(10).
	Scan(ctx)
if err != nil {
	...
}

... lot of code ...

// in some case, if something, I want to preload relations
if something {
	db.???(&customers).
		Relation("Address.City.Country"). // may preload with WHERE IN + JOIN (or only WHERE IN)
		Relation("Payments.Rental"). // preload with WHERE IN
		Scan(ctx)
}


// I can make this but it will reload the customers... :\
err := db.NewSelect().
	Model(&customers).
	Where("customer_id IN (?)", bun.In(customerIds)).
	Relation("Address.City.Country"). // preload with JOIN
	Relation("Payments.Rental"). // preload with WHERE IN
	Scan(ctx)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions