maz

maz

Ecto Query preloading complex association

I’m doing a fairly complex join where I want to preload an array of ContentMediaItems (called :contents) that are nested in an association, Channel

But it appears that ecto thinks I’m referencing the MediaItem in the preload even though I’m doing:

preload: [channel: {chan, contents: chancon}],

and name the associations previously:

join: chan in assoc(con, :channel),
join: chancon in assoc(chan, :contents),

So why does the exception

    ** (Ecto.QueryError) field `MyWord.Multimedia.MediaItem.channel` in preload is not an association in query:

appear?

Here is the full query along with the error below it.

    from(m in MediaItem,
      join: con in ContentMediaItems,
      on: m.id == con.media_item_id,
      where: is_nil(m.published_at) == false,
      join: chan in assoc(con, :channel),
      where: chan.id == con.channel_id,
      join: chancon in assoc(chan, :contents),
      on: chancon.channel_id == chan.id,
      join: org in Org,
      on: m.org_id == org.id,
      where: org.slug == ^org_slug,
      order_by: [{:desc, :published_at}],
      preload: [:mediaitemartifacts],
      preload: [channel: {chan, contents: chancon}],
      select: %{id: m.id, inserted_at: m.inserted_at, media_item: m, channel: chan}
    )

Exception:

** (Ecto.QueryError) field `MyWord.Multimedia.MediaItem.channel` in preload is not an association in query:

from m0 in MyWord.Multimedia.MediaItem,
  join: c1 in MyWord.Channels.ContentMediaItems,
  on: m0.id == c1.media_item_id,
  join: c2 in MyWord.Channels.Channel,
  on: c2.id == c1.channel_id,
  join: c3 in MyWord.Channels.ContentMediaItems,
  on: c3.channel_id == c2.id and c3.channel_id == c2.id,
  join: o4 in MyWord.Orgs.Org,
  on: m0.org_id == o4.id,
  where: is_nil(m0.published_at) == false,
  where: c2.id == c1.channel_id,
  where: o4.slug == ^"myword-app",
  order_by: [desc: m0.published_at],
  limit: ^41,
  select: %{id: m0.id, inserted_at: m0.inserted_at, media_item: m0, channel: c2},
  preload: [:mediaitemartifacts],
  preload: [channel: {c2, contents: c3}]

Relevant schema information:

schema "mediaitems" do
    has_many(:mediaitemartifacts, MyWord.Multimedia.MediaItemArtifact)
    many_to_many(:channels, Channel, join_through: "channels_content_media_items", unique: true)

schema "channels" do
  has_many(:contents, ContentMediaItems)

schema "channels_content_media_items" do
  belongs_to :channel, Channel
  belongs_to :media_item, MediaItem

Marked As Solved

jswanner

jswanner

When using assoc/3 or preload the name of the association given as an argument needs to match the name given in the schema (including pluralization).

In the case of your error message, I’m pretty sure you need to use :channels not :channel.

Also Liked

sodapopcan

sodapopcan

Chiming in to say: when preloading in the query with complex joins like that, it can often be very slow. This is because only one query is run which returns a massive, de-normalized table that has to filtered down by Elixir. I would try it out with Repo.preload as well to see if there is a difference. There might not be, but from experience I once had a response time go from over 30 seconds to under 1 second just by switching to Repo.preload. Fewer queries aren’t always better!

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
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
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42842 311
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
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
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30840 112
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
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
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New

We're in Beta

About us Mission Statement