Ecto为查询声明架构

时间:2016-09-12 20:48:13

标签: elixir ecto

我正在尝试运行此查询:

select last_sd.*
from
  (select distinct(sensor_id) from sensor_data) s LEFT JOIN LATERAL
  (select * from sensor_data sd1 where sd1.sensor_id = s.sensor_id order by sd1.received_at desc limit 1) last_sd ON true

我最接近的是:

from s in IotInABox.SensorData, distinct: true, select: s.sensor_id
|> join(:left_lateral, [s], sd in fragment("select * from sensor_data sd1 where sd1.sensor_id = ? order by sd1.received_at desc limit 1", s.sensor_id))
|> select([s, sd], sd)
然而,这部分工作,因为它抛出

PostgreSQL requires a schema module when using selector "f1" but none was given. Please specify a schema or specify exactly which fields from "f1" you desire in query

意思是因为我没有from s in SensorData,所以它不知道要使用哪个ecto模型,

有没有办法告诉ecto哪个架构用作查询结果?

1 个答案:

答案 0 :(得分:2)

也许并不完美,但这样的事情对我有用(在下面的例子中使用我项目中的名字):

keys = Division.__schema__(:fields)
query = from d in "divisions", select: map(d, ^keys)
result = Repo.all(query) |> Enum.map(&(struct(Division, &1)))
  1. 首先,您需要架构字段列表
  2. 以地图形式选择所有密钥
  3. 将地图映射回结构^^