动态预加载表

时间:2018-09-26 09:17:31

标签: elixir ecto

我有这个查询,可以动态地预加载表。

 assoc_models = [:example]
          from(
            q in queryable,
            preload: ^assoc_models
          )

结果是这样的:

 #Ecto.Query<from j in TestModel.Join, preload: [[:example]]>

assoc_models内部可以有任意数量的表

预紧力后还有另外一对要去除的支架。

有没有一种方法可以从列表中获取所有项目,然后将其置于预加载状态,以删除这样的括号

  #Ecto.Query<from j in TestModel.Join, preload: [:example]>

谢谢

2 个答案:

答案 0 :(得分:2)

我假设您要自动预加载任何给定模式的所有关联。模式模块具有一个.__schema__/1函数/宏。要获得这样的关联列表:

iex(15)> OneChat.Schema.Message.__schema__(:associations)
[:user, :channel, :edited_by, :stars, :attachments, :reactions, :mentions]

在给定架构模块的情况下,这是一个自动预加载查询的简单模块。

defmodule AutoPreload  do
  def preload(query, schema_module) do
    preloads = schema_module.__schema__(:associations)
    Ecto.Query.preload(query, ^preloads)
  end
end

在这里起作用:

iex(17)> AutoPreload.preload(from(m in OneChat.Schema.Message), OneChat.Schema.Message)
#Ecto.Query<from m in OneChat.Schema.Message,
 preload: [[:user, :channel, :edited_by, :stars, :attachments, :reactions, :mentions]]>

答案 1 :(得分:0)

没有多余的括号对。如您所见,preloadsassocsput together进入同一列表。

此列表中有一对括号,而您的预紧力中有一对括号。

相关问题