预加载嵌套关联查询

时间:2018-05-04 20:27:33

标签: elixir phoenix-framework ecto

我试图在查询预载中进行排序。这是我的问题:

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
      )

但是这不起作用并且给我一个语法错误:

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

有人知道如何使用Ecto预加载嵌套属性吗?

1 个答案:

答案 0 :(得分:1)

您收到此SyntaxError,因为括号不平衡。

以下代码修复了此问题:

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
  )

但实际上,如果你有Projecthas_many rowsRowhas_many images,那么预加载这些关联就是就像这样简单:

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