I have some troubles making a query with Ecto :
SavedDevice
- belongs_to Devices
- belongs_to User
Device
- has_many SavedDevices
- has_many DeviceLocations
DeviceLocation
- belongs_to Devices
I want to load the SavedDevices belonging to a User, with the latest DeviceLocation saved.
This solution works fine :
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
But it loads every DeviceLocations. This is a problem because there can be thousands of them and I only need the last one.
When I add limit: 1 to location_query, it returns just 1 DeviceLocation for all the Devices and not 1 Devicelocation per Device.
Any idea?