I have 3 models as Vendor
, VendorModel
and Camera
. I am doing this query to get VendorModels
.
query = from vm in VendorModel,
join: v in Vendor, on: vm.vendor_id == v.id,
where: like(fragment("lower(?)", vm.name), ^("%#{search}%")),
where: like(fragment("lower(?)", v.name), ^("%#{search}%"))
models = query |> add_sorting(column, order) |> preload(:vendor) |> Evercam.Repo.all()
I am appending order_by
through a method add_sorting which only adds up the order_by
such as
defp add_sorting(query, "exid", order) do
from [vm, _v] in query,
order_by: [{^sort_order(order), vm.exid}]
end
After getting all models I am doing Enum.reduce
to format an object on of all models. On each VendorModel
there is an association with Camera
, And I am getting a count for each model referenced in cameras such as
Enum.reduce(display_start..index_end, [], fn i, acc ->
model = Enum.at(models, i)
vm = %{
vendor_exid: model.vendor.exid,
exid: model.exid,
camera_count: Camera |> where(model_id: ^model.id) |> Evercam.Repo.all() |> Enum.count(),
}
acc ++ [vm]
end)
this always ran another query for each model to get the count of cameras, Is there any possibility to add this count query to above the first query. And it also supports order by?
I have read about subquery and group_by but I couldn’t make it work.
PS: Already tried stackoverflow for this question: https://stackoverflow.com/questions/54510058/how-to-join-multiple-models-in-on-ecto-query-ecto