我有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的集合.
你能告诉我一个很好的例子吗 - 如何预加载"活跃的"api_keys?
关于Ecto的这个问题可能与您相关.
目前您有两种选择:
使用Enum.map
使用提取后join
和select
:
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)