【发布时间】:2021-10-30 01:12:24
【问题描述】:
我在使用Ecto 进行查询时遇到了一些麻烦:
SavedDevice
- belongs_to Devices
- belongs_to User
Device
- has_many SavedDevices
- has_many DeviceLocations
DeviceLocation
- belongs_to Devices
我想加载属于 User 的 SavedDevices,并保存最新的 DeviceLocation。
这个解决方案很好用:
def list_pdevices_locations(user, limit \\ 0) do
location_query = from(dl in DeviceLocation, order_by: [desc: :inserted_at])
query =
from(d in ProvisionedDevice,
preload: [device_info: [locations: ^location_query]],
limit: ^limit
)
if user.is_admin do
Repo.all(query)
else
Repo.all(from(d in query, where: d.user_id == ^user.id))
end
end
但它会加载每个 DeviceLocations。这是一个问题,因为可能有数千个,而我只需要最后一个。
当我将 limit: 1 添加到 location_query 时,它只返回 1 个 DeviceLocation 用于所有 设备 而不是 1 个 Devicelocation 每 设备。
有什么想法吗?
【问题讨论】:
标签: elixir phoenix-framework ecto