Ecto 在关联上运行

Kam*_*han 1 elixir phoenix-framework

我运行这样的查询:

query = from q in MY.Model, preload: [:accoc], where: q.accoc_field in [10, 11]
Repo.all(query)
Run Code Online (Sandbox Code Playgroud)

这给了我错误:

** (Ecto.QueryError) iex:32: field `accoc_field` in `where` does not exist in schema MY.Model in query:
Run Code Online (Sandbox Code Playgroud)

所以,基本上我正在尝试编写一个查询,例如:

select * from my_model m join assoc a on m.assoc_id = a.id where a.assoc_field in (10, 11)
Run Code Online (Sandbox Code Playgroud)

我知道我可以使用 Ecto 中的联接来编写上述查询,但是在使用预加载时如何做到这一点?

Vir*_*iil 5

我希望这里最好的解决方案是遵循 SQL 代码。

我们需要连接另一个表,因此我们需要调用Ecto.Query.join/5函数,而不是预加载。

例如,假设我们需要检索创建了具有特定部分的帖子的用户:

from u in User,
join: p in assoc(u, :posts),
where: p.section in ["elixir", "phoenix"],
select: u
Run Code Online (Sandbox Code Playgroud)

在Repo.all执行此查询后,我们将获得所需用户的列表。在这里,如果我们想向用户填充帖子 - 我们可以调用Repo.preload