You could also use a join and select…
I dont know what your schema looks like, but heres a stab at some code that should get you close to what you need:
WARNING: UNTESTED
# Assuming user has_many :likes, through: Thread
query = from u in User,
join: l in assoc(u, :likes),
select: {u, l}
results = Repo.all(query)
Thank you, but preloads is not the entire solution here I believe. Using preloads I can do something like this:
def threads_with_like_level_for_user(user) do
thread_like_query =
from tl in MyApp.ThreadLike,
where: tl.user_id == ^user.id,
select: map(ti, [:like_level])
from t in MyApp.Thread,
left_join: tl in MyApp.ThreadLike,
on: t.id == tl.thread_id and tl.user_id == ^user.id,
preload: [thread_likes: ^thread_like_query]
end
It would really help to see your Schemas, but assuming ThreadLike.like_level is singular then what about something like:
def thread_with_like_level_for_user(user) do
from t in MyApp.Thread,
left_join: tl in MyApp.ThreadLike, on: ti.id == tl.thread_id and tl.user_id == ^user.id,
select: %{id: t.id, title: t.title, body: t.body, user_like_level: tl.thread_likes}
end
If I try to include a has_many association here, like this:
def thread_with_like_level_for_user(user) do
from t in MyApp.Thread,
left_join: tl in MyApp.ThreadLike, on: ti.id == tl.thread_id and tl.user_id == ^user.id,
join: p in assoc(t, :posts),
select: %{id: t.id, title: t.title, body: t.body, user_like_level: tl.like_level, posts: p}
end
It doesn’t return a list of posts, but instead just a map. Can I get the association in there as well?