Owens

Owens

Ecto get records where association count is 0

I couldn’t find an answer to this from searching so thought I would make a post about it.

I’m trying to get a list of Users who have not created Office Hours. Essentially, records where the association does not exist or the count is 0.

This article helped but was too advanced for what I’m doing.

The suggestion is to user LEFT OUTER JOIN.

SELECT * FROM rentals
    LEFT OUTER JOIN unavailabilities
      ON (unavailabilities.rental_id = rentals.id)
  WHERE rental_id IS NULL;

Converting this to my use case in Elixir leads to:

query = from u in User,
  left_join: o in OfficeHour,
  on: [o.user_id: u.id],
  where: user_id == nil

I’m not sure if this is correct, or what would be the way to write this using the pipe operators? Any help is appreciated.

Marked As Solved

hauleth

hauleth

While approach used by @fuelen will work, it is far from optimal one. The best would be using NOT EXISTS, but Ecto do not support it directly, so we need to fallback to fragment:

query =
  from u in User, where: fragment("NOT EXISTS (SELECT * FROM office_hours h WHERE h.user_id = ?)", u.id)

This would allow query planner to optimise this query as much as possible.

Also Liked

fuelen

fuelen

just run the query and see what happens :slight_smile:
Solution in SQL looks correct, but not the Elixir version. Correct snippet is

query = from u in User,
  left_join: o in OfficeHour,
  on: o.user_id == u.id,
  where: is_nil(o.user_id)

If you have declared an association in User struct for :office_hours then query can be simplified a bit to this:

query = from u in User,
  left_join: o in assoc(u, :office_hours),
  where: is_nil(o.user_id)

and using pipe operators if you like them:

User
|> join(:left, [u], o in assoc(u, :office_hours))
|> where([..., o], is_nil(o.user_id))

Where Next?

Popular in Questions Top

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
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
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

Other popular topics Top

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New

We're in Beta

About us Mission Statement