go-gorm / gen

Gen: Friendly & Safer GORM powered by Code Generation
https://gorm.io/gen/
MIT License
2.29k stars 296 forks source link

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

Open hidenami-i opened 5 months ago

hidenami-i commented 5 months ago

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.

lloydw commented 3 days ago

I’ve just encountered the same issue, did you find a solution to this?

Thanks