如何在 Ecto Query 中创建条件连接?

How to create conditional join in Ecto Query?

我有 2 个模型 - 用户和 ApiKey(用户 has_many api_keys),我正在尝试创建条件连接。我的意思是我想用他的活动 ApiKeys 加载单个查询用户。我当前的代码看起来像

query = from u in User, 
        join: a in assoc(u, :api_keys), 
        where: u.email == ^email,
        preload: [api_keys: a]
user = Repo.one(query)
Repo.preload user, api_keys: (from a in ApiKey, where: a.is_active == true)

但不幸的是,正如我所见 - 当数据已经预加载时,预加载方法无法更改 api_keys 的集合。

你能给我举个好例子吗 - 如何只预加载 "active" api_keys?

Ecto 上的

This issue 可能与您相关。

目前您有两个选择:

使用 joinselect 获取后使用 Enum.map:

query = from u in User, 
        join: a in assoc(u, :api_keys), 
        where: u.email == ^email,
        where: a.is_active == true,
        select: {u, a}
user = Repo.one(query) |> Enum.map(fn ({u, a}) -> %{u | api_keys: a} end)

使用查询作为 Ecto.Query.preload/3 的参数:

api_key_query = from a in ApiKey, where: a.is_active == true
query = from u in User, 
        join: a in assoc(u, :api_keys), 
        where: u.email == ^email,
        preload: [api_keys: ^api_key_query]
user = Repo.one(query)