Skip to content

Accessing field.RelationField outside of query instance in repository layer #1169

@ShuheiIwamoto

Description

@ShuheiIwamoto

Your Question

Is there a way to access field.RelationField outside of the query instance in the current generated code by gorm.gen?

We want to implement a repository method that accepts field.RelationField as variadic arguments for flexible preloading, like this:

func (r *userRepository) GetUserWithPreloads(ctx context.Context, id uint, preloads ...field.RelationField) (*model.User, error) {
    query := r.q.User.WithContext(ctx).Where(r.q.User.ID.Eq(id))
    
    for _, preload := range preloads {
        query = query.Preload(preload)
    }
    
    return query.First()
}

Currently, it seems we can only access field.RelationField through the query instance (e.g., query.User.Posts.RelationField). Is there any way to get these relation fields without the query instance, or is there an alternative approach we should consider to achieve flexible and type-safe preloading in the repository layer?

The document you expected this should be explained

https://gorm.io/gen/

Expected answer

We're looking for either:

  1. A way to access field.RelationField without using the query instance in the current generated code.
  2. An alternative approach to implement flexible and type-safe preloading in the repository layer using gorm.gen.
  3. Confirmation that this is not possible with the current implementation, and whether there are plans to support this kind of usage in future versions.

Thank you for your assistance.

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