Jas*_*n G 11 elixir ecto phoenix-framework
我正在尝试以编程方式将预加载附加到我的某个具有has_many, through:关系的模型的查询中.
我的模块:
defmodule MyApp.Chemical do
use MyApp.Web, :model
schema "chemicals" do
has_many :company_chemicals, MyApp.CompanyChemical
has_many :companies, through: [:company_chemicals, :companies]
field :name, :string
end
def with_companies(query) do
from chem in query,
left_join: comp_chem in assoc(chem, :company_chemicals),
join: company in assoc(comp_chem, :company),
preload: [companies: company]
end
end
defmodule MyApp.Company do
use MyApp.Web, :model
schema "companies" do
has_many :company_chemicals, MyApp.CompanyChemical
has_many :chemicals, through: [:company_chemicals, :chemicals]
field :name, :string
end
end
defmodule MyApp.CompanyChemical do
use MyApp.Web, :model
schema "company_chemicals" do
belongs_to :chemical, MyApp.Chemical
belongs_to :company, MyApp.Company
end
end
Run Code Online (Sandbox Code Playgroud)
使用这些模型,MyApp.Chemical.with_companies/1工作按预期返回一个查询,该查询将生成带有填充:companies字段的化学品,但我试图通过关联表以编程方式预加载字段来创建类似以下的函数:
def preload_association(query, local_assoc, assoc_table, assoc_table_assoc) do
from orig in query,
left_join: association_table in assoc(orig, ^assoc_table),
join: distal in assoc(association_table, ^assoc_table_assoc),
preload: [{^local_assoc, distal}]
end
Run Code Online (Sandbox Code Playgroud)
但是,由于该preload: [{^local_assoc, distal}]行,此函数将无法编译.
如何预加载一个has_many的关联?谢谢.
Jos*_*lim 15
你是否以任何方式过滤你的联接?因为,如果你不是,你应该调用preload:
query = from c in MyApp.Company, where: ...
companies = Repo.all(query)
companies_with_chemicals = Repo.preload(companies, :chemicals)
Run Code Online (Sandbox Code Playgroud)
要么:
query = from c in MyApp.Company, preload: :chemicals
companies_with_chemicals = Repo.all(query)
Run Code Online (Sandbox Code Playgroud)
这将是快过因为它两个单独的查询,减少从处理的整体结果集的大小companies_size * chemicals_size来companies_size + chemicals_size.
请注意,您也应该能够加入has_many :through.