Reputation: 19456
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?
Upvotes: 3
Views: 320
Reputation: 120990
Use Kernel.elem/2
:
{Link, 10} |> elem(1)
#⇒ 10
So, within your code:
query
|> Repo.all()
|> how_do_you_get_tuple()
|> elem(1)
Upvotes: 1
Reputation: 5963
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
.
Upvotes: 2