Postgrex - 查询返回不明确的列引用错误

Postgrex - query returning an ambiguous column reference error

我有以下疑问:

def user_contacts(provider_id, filter) do
  query =
    from(
      u in User,
      preload: [:groups],
      where: u.provider_id == ^provider_id and u.type != "company"
    )

  query
  |> filter_sector(filter)
  |> filter_availability(filter)
end

defp filter_sector(query, %{"sector" => "Asset Management & Investment Funds"}) do
  query
  |> join(:inner, [u], p in Profile, p.user_id == u.id)
  |> where([u, p], fragment("(sectors->>'asset' = ?)", "true"))
end

defp filter_sector(query, _), do: query

defp filter_availability(query, %{"availability" => "now"}) do
  query
  |> join(:inner, [u], p in Profile, p.user_id == u.id)
  |> where([u, p], ^Date.utc_today >= p.placement_availability)
end

defp filter_availability(query, _), do: query

我收到以下错误: ERROR 42702 (ambiguous_column): column reference "sectors" is ambiguoussectorsProfile 中的嵌入式架构。

我尝试通过将 filter_sector 查询的结构改写成这个来解决这个问题:

from(
  q in query,
  join: p in Profile,
  on: p.user_id == q.id,
  where: fragment("(sectors->>'asset' = ?)", "true")
)

但我仍然遇到同样的错误。奇怪的是,当过滤器只有一个 "sector" 值或一个 "availability" 值时,查询有效,但当两个值都存在时,就会出现错误。

在不查看整个查询的情况下,我只能推测,但您可能在该连接中还有另一个 table,上面有一个 sectors 字段。或者可能配置文件被连接了两次。如果您包括完整的错误消息、堆栈跟踪以及生成的查询,将有助于确认这种怀疑。

如果是这种情况,您可以通过完全限定 sectors 字段来修复它,这是编写查询的首选方式:

query
|> join(:inner, [u], p in Profile, p.user_id == u.id)
|> where([u, p], fragment("(?->>'asset' = ?)", p.sectors, "true"))

现在应该没有歧义了