Reputation: 3970
I have Hanami models User
and UserInfo
that have has_one
association.
Repositories look the following:
class UserInfoRepository < Hanami::Repository
end
class UserRepository < Hanami::Repository
associations do
has_one :user_info
end
end
Question: who can I join and load both tables with one query? (I am looking for something similar to Rails' includes
).
So far I've tried
def users_with_info
users.join(:user_info)
end
It does the join, but does not select columns from user_infos
table.
Thanks in advance.
Upvotes: 2
Views: 870
Reputation: 795
When you fetch data via a Repository in Hanami the result set is mapped into entities.
By default the UserRepository
will map to the User
entity. I'm guessing that that entity does not have attributes for the columns from user_info
.
What you need to do is create an Entity that can contain the data that you want to fetch from the database and then call .as(ThatEntityYouCreated)
on the result set. E.g.,
def users_with_info
users.join(:user_info).map_to(UserWithInfo)
end
If you do not want to create an Entity and just want to get a plain hash, you can do this:
users.join(:user_info).map.to_a
However, I consider this to be a crutch. You should not return Hashes from your Repository methods.
Upvotes: 2
Reputation: 60
I believe we faced this exact issue with a teammate of mine on one of our Hanami project, and this is how we solved it.
We basically bypassed Hanami repository, going straight to the underlying ROM relation, using ROM::Relation#wrap
in order to get our User
entity joined with the entity of interest.
Let met know if it helped you, or if you need more details. Cheers!
Upvotes: 1