Ecto:预加载已排序的关联

时间:2017-11-15 21:08:30

标签: ecto

我想根据嵌套关联中Campaign的数量对Conversion的查询进行排序。我想在预加载Campaign时在另一个查询中执行此操作:

CampaignGroup
|> Repo.all()
|> Repo.preload(campaigns: Campaign |> Campaign.sorted_by_number_of_conversions)

但是这引发了一个Ecto错误:ERROR 42803 (grouping_error): column "c4.id" must appear in the GROUP BY clause or be used in an aggregate function

我的排序查询如下所示:

defmodule MyApp.Campaign
  def sorted_by_number_of_conversions(query) do
    from campaign in query,
    join: company in assoc(campaign, :company),
    join: good in assoc(company, :goods),
    join: conversion in assoc(good, :conversion),
    group_by: [campaign.id, company.id],
    order_by: [desc: count(conversion.id)]
  end
end

原始SQL查询如下所示:

SELECT c0."id", c0."description", c0."start_date", c0."name", c0."end_date", c0."url", c0."logo", c0."company_id", c0."inserted_at", c0."updated_at", c4."id" FROM "campaigns" AS c0 
INNER JOIN "companies" AS c1 ON c1."id" = c0."company_id" 
INNER JOIN "goods" AS g2 ON g2."company_id" = c1."id" 
INNER JOIN "conversions" AS c3 ON c3."good_id" = g2."id" 
INNER JOIN "campaign_groups" AS c4 ON c4."id" = ANY($1) 
INNER JOIN "campaigns_campaign_groups" AS c5 ON c5."campaign_group_id" = c4."id" WHERE (c5."campaign_id" = c0."id") 
GROUP BY c0."id", c1."id" 
ORDER BY c4."id", count(c3."id") DESC

在预加载之外运行查询可以正常工作:

Campaign 
|> Campaign.sorted_by_number_of_conversions()
|> Repo.all()

但是这个查询不应该在preload语句中起作用吗?

我的模式看起来像这样:

转换:

schema "conversions" do
  belongs_to :good, MyApp.Good
end

好:

schema "goods" do
  has_one :conversion, MyApp.Conversion
  belongs_to :company, MyApp.Company
end

公司:

schema "companies" do
  has_many :goods, MyApp.Good
  has_many :campaigns, MyApp.Campaign
end

广告系列:

schema "campaigns" do
  belongs_to :company, MyApp.Company
  many_to_many :campaign_groups, MyApp.CampaignGroup, join_through: "campaigns_campaign_groups"
end

CampaignGroup:

schema "campaign_groups" do
  many_to_many :campaigns, MyApp.Campaign, join_through: "campaigns_campaign_groups"
end

0 个答案:

没有答案