go-rel / rel

:gem: Modern ORM for Golang - Testable, Extendable and Crafted Into a Clean and Elegant API

Home Page:https://go-rel.github.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Fetching joined records alongside with main entity

skolodyazhnyy opened this issue · comments

Hey,

I wonder what would be suggested approach to fetch composite records (those combined of entity and a join entity). In the documentation there is example on how to perform join and then filter results by values in joined tables, but there is nothing about fetching these joined records.

As an example, I want to describe a simplified version of issue I'm having. Data model here does not make much sense, but it's just to illustrate the problem. Let's say we have a table of users (id, name) and a separate table with number of user followers (user_id, followers_count), it's a one-to-one relation.

I want to be able to find users with certain number of followers so I can use join and then where clause, but I would like to also fetch number of followers in the same query (it's joined already anyway) instead of using prefetch.

var users []Users
err := repo.FindAll(ctx, &users, rel.Join("follower_stats").Where(where.Gt("follower_stats.followers_count", 100)))

This code example above will only populate user data, then I can preload follower_stats for each user, but it seems somewhat wasteful as number of users can be pretty high.

Hi,

loading association via join is not supported at the moment, the only way to load association at the moment is by using different preload query

Thanks for reply. I actually figured out kind of workaround by creating a new struct with fields from both entities, something like

type UserWithFollowers struct {
  ID string 
  Name string 
  FollowersCount int
}

I'm using rel.Select("users.*", "follower_stats.followers_count") to combine fields from both tables. It worked for my use case, maybe will help someone else. Although converting UserWithFollowers back to User is a bit of painful. Maybe if rel would allow populating embedded structs I could simplify this bit.

Thanks for this suggestion, it's actually not very hard to implement as long as has many association is not supported for this kind of use case

I've created a PR to support this: #290
however at the moment you still need to explicitly list the associated field you want to embed. I'm thinking to make it easier maybe by adding a special method to expand association fields or maybe post-processor to expand "associations.*" in rel.Select` function