Search code examples
elixirphoenix-frameworkecto

preload nested association query


I'm trying to order by in a query preload. This is my query:

query =
      from(
        p in Project,
        preload: [rows: {from(r in Row, order_by: r.index), [images: from(r in Row, order_by: r.index)}]],
        where: p.user_id == ^user_id
      )

But this doesn't work and gives me a syntax error:

** (SyntaxError) web/controllers/project_controller.ex:11: "{" is missing terminator "}". unexpected token: ")" at line 13

Does anybody know how to preload nested attributes with Ecto?


Solution

  • You receive this SyntaxError, because the brackets are not balanced.

    The following code has this problem fixed:

    query =
      from(
        p in Project,
        preload: [rows: {from(r in Row, order_by: r.index), images: from(r in Row, order_by: r.index)}],
        where: p.user_id == ^user_id
      )
    

    But actually, if you have Project, which has_many rows and Row, which has_many images, then preloading these association is going to be as simple, as this:

    from p in Project, preload: [rows: :images]