def list_links_count do
query =
from l in Link,
join: c in Click, as: :click,
where: c.link_id == l.id,
group_by: l.id,
select: {l, count(l.id)}
query |> Repo.all
end
I've got a function that counts that number of clicks per link. The problem is with the final data structure, which is of the form {Link, 10}. What I'd really like to do is have it put_in the total, so I can access it more easily in a view, something like link.click_count. Is that possible?
Do you have the virtual field on your Ecto schema for Link? If not, you'll want to add it:
field(:click_count, :integer, virtual: true)
Then your select could look something like this:
select: %{l | click_count: count(l.id)}
Since you now have a click_count key in your Link structs, you can put that key and still have a list of Links. So you should be able to access link.click_count.
Use Kernel.elem/2:
{Link, 10} |> elem(1)
#⇒ 10
So, within your code:
query
|> Repo.all()
|> how_do_you_get_tuple()
|> elem(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With