动态预加载表

Preload tables dynamically

我有一个动态预加载表的查询。

 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]>

谢谢

没有多余的一对括号。如您所见,preloadsassocs 在同一个列表中 put together

一对括号围绕着这个列表,另一对围绕着你的预载。

我假设您想自动预加载任何给定模式的所有关联。模式模块有一个 .__schema__/1 function/macro。要获取这样的关联列表:

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]]>