Yama

Yama

Ecto query call when using aggregate function

Sorry for asking something that has been mentioned a few times here but would like some help to get a better understanding. What I’m trying to do is be able to return a list of tags with the number of posts that has a tag associated with it.

    subquery = from(pt in PostTag, select: %{postCount: count(pt.tag_id)}, group_by: pt.tag_id)

    query =
      from(t in Tag,
        join: pt in subquery(subquery),
        on: t.id == pt.tag_id,
        where: ilike(t.name, ^search),
        select: %{id: t.id, name: t.name, count: pt.postCount},
        group_by: t.id
      )

We want to be able to return something like %{id: "1", count: 4} where the count is the number of posts associated with that tag. I currently have 3 tables, Post, Tag, and PostTags which connects the other two as many to many association.

I was hoping to get a better understanding of why I’m getting this error t0.id" must appear in the GROUP BY clause or be used in an aggregate function.

Thanks for the help and clarity in regards to this problem and pointing in the right direction in solving it.

Most Liked

Yama

Yama

I believe I may have found a solution. Would love some input if there is a better approach or maybe some flaws so what seems to be working. Thanks again

  def get_tags(search) do
    subquery =
      from(pt in PostTag,
        select: %{tag_id: pt.tag_id, postCount: count(pt.tag_id)},
        group_by: pt.tag_id
      )

    query =
      from(t in Tag,
        join: pt in subquery(subquery),
        on: t.id == pt.tag_id,
        where: ilike(t.name, ^search),
        select: %{id: t.id, name: t.name, count: pt.postCount}
      )

    # from(t in Tag, join: p in assoc(:posts), select: t.name)
    Repo.all(query)
  end

Last Post!

Nicodemus

Nicodemus

I found this thread while researching options for adding aggregated results to a list, and would like to propose a different way to do it that doesn’t require any extra mapping or struct building for anyone else looking. Apologies for necro-posting.

First, add a virtual field to the Tag schema:

field :posts_count, :integer, virtual: true

Then simply merge the aggregate result into the existing list of returned structs, which if there is no select in the query it defaults to the full schema (equivalent to select: t.)

def list_tags_with_posts_count do
  Repo.all(
    from t in Tag,
      left_join: p in assoc(t, :posts),
      group_by: t.id,
      order_by: [asc: :name],
      select_merge: %{posts_count: count(p.id)}
  )
end

Where Next?

Popular in Questions Top

jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New

Other popular topics Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement