alaister

alaister

Selecting fields in preloaded joins Ecto

Hi,
I have the following ecto query:
post_query = from p in Post, where: p.id == ^id, join: c in assoc(p, :comments), join: u in assoc(c, :user), preload: [comments: {c, :user}]

How do I select the following fields: p.title, p.content, p.comments, c.comment, c.inserted_at and u.name?
I’m having trouble with this because of the wired joins I’m doing (Still learning). Also this query actually runs two queries on the database. Is there any way to do it all in one?

Thanks,
Alaister

Most Liked

Linuus

Linuus

This should make only one DB query.

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    join: u in assoc(c, :user), 
    preload: [comments: {c, user: u}]

Regarding selecting association fields, you can do something like this (not tested)

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    join: u in assoc(c, :user), 
    select: %{id: p.id, title: p.title, comments: p.comments, name: u.name}

Not sure exactly what you want to get back but that’s one way to select fields :slight_smile:

Linuus

Linuus

I had a discussion about this on IRC and it seems to often be better to not join manually and just preload the data (and let it do multiple queries).

This would issue one request to the DB:

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    join: u in assoc(c, :user), 
    preload: [comments: {c, user: u}]

But it would return a lot of excessive data because the join would cause the Post data to be sent for each comment (due to how SQL works). Ecto hides this though by throwing away the excessive data.
You can se this if you run something like the query I wrote before:

post_query = 
  from p in Post,
    where: p.id == ^id,
    join: c in assoc(p, :comments),
    select: %{id: p.id, comments: c}

It will return one struct for each Comment so if a Post has two comments:

[%{
  id: 1,
  comments: %{id: 123, text: "foo"}
}, %{
  id: 1, 
  comments: %{id: 124, text: "Next comment"}
}]`

You don’t see this behaviour when running without the select statement because Ecto takes care of mapping the data.

When just preloading:

post_query = 
  from p in Post,
    where: p.id == ^id,
    preload: [comments: [:user]]

This would issue three requests but no excessive data so in many cases it is actually more efficient (Ecto even does the requests in parallell when possible).
For example, if the same user has made all the comments, the user would only be fetched once. When joining, the user would be returned for each comment.

So, unless you know you have a bottleneck here it may not be worth it…

(I’m quite new to Ecto, so if someone sees something wrong here, please let me know! :slight_smile: )

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe
query = from u in UserSchema,
       where: u.id == ^id,
       left_join: c in assoc(u, :subscribers),
       preload: [subscribers: c],
       select: struct(u, [
         :id,
         :name,
         :mobile,
         :last_name,
         :mobile,
         :status,
         :role,
         :inserted_at,
         :updated_at,
       ])
benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

One more typo, try again.

Molly101

Molly101

You can use a pattern matching here to get only those fields You’re interested in, i.e. %{title: title, content:content, comments: comments, user: %{name: name}} = Repo.get!(post_query) and then You can pass comments though Enum.Map. In Phoenix app You can also use View - “show.json” approach to convert result of Your ECTO query to a Map with the fields that You need… Because anyway You can’t just encode ECTO query result to JSON…

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
Kagamiiiii
Student & New to elixir. Nice language. I want to convert a english character, e.g. “a”, which is stored in a variable, to it’s asci...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

We're in Beta

About us Mission Statement