PragTob

PragTob

Preload association count/if there are associations records

:wave:

Relatively common setup:

I have a Thing which has_many SubThing. In the index view (showing many Things) I want to display a link or a text if there are any “sub things”. Otherwise not.

Of course I could just Repo.preload(:sub_things) but I don’t need them here so I wanna be light on the db/memory etc.

I know that I can write some query that returns me its own data structure telling me which Thing record has how many SubThings (or id any at all) and I could use that second data structure to display/not display them. I don’t have that query but I’m confident that I can write it with relative ease :smiley:

I think this is a relatively common problem, so the question is: “Is there a better/standard way to do this?” (my googling came up empty)

If I could wish for something then my Thing struct would have an additional attribute like:

%Thing{
  sub_things_exist?: true/false
  # or / and
  sub_things_count: 5
}

And I could get there with Repo.preload(:sub_things_exist?) or something similar.

Just to be clear I don’t want to introduce a counter cache (yet) it’s fine if it’s still queried from the database dynamically but ideally in one big query (this is on an index page with a lot of elements).

Thanks and cheers as always! :green_heart:

Marked As Solved

hauleth

hauleth

You do not need that subquery, if this is just association then:

query = from t in Thing,
  join: s in assoc(s, :sub_thing),
  group_by: t.id
  select_merge: %{sub_thing_count: count(s.id)}

Will work as expected (DB optimisers are good enough to not fetch whole entries.

Also Liked

LostKobrakai

LostKobrakai

Add field :sub_thing_count, :integer, virtual: true to your schema of Thing and instead of Thing use the following for querying:

sub_query = from s in SubThing, select: map(s, [:id, :thing_id])
query = from t in Thing,
  join: s in subquery(sub_query), on: s.thing_id == t.id, 
  group_by: t.id
  select_merge: %{sub_thing_count: count(s.id)}

You could skip the subquery and then join the whole table. What is faster probably depends on the column size of the sub_thing table.

PragTob

PragTob

Thanks a bunch everyone, haven’t tried it yet but looks like exactly what I need :dancer:

LostKobrakai

LostKobrakai

I’m not sure how it would work in ecto, but lateral joins would basically do what you’re thinking of:

SELECT thing.id, sub_thing.available IS NOT NULL AS sub_thing_available 
FROM thing AS thing
LEFT JOIN LATERAL (
	SELECT true AS available 
	FROM sub_thing
	WHERE thing_id = thing.id
	LIMIT 1
) AS sub_thing ON true

Where Next?

Popular in Questions Top

New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52673 488
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement