How can I use "count" and "group by" in Prisma 2?

18.3k Views Asked by At

I have this function which works:

export const tagsByLabel = async (params) => {
  const findManyParams = {
    where: { userId: userIdFromSession },
    orderBy: { title: "asc" },
  };
  if (params) {
    const { searchTerm } = params;
    findManyParams.where.title = { contains: searchTerm };
  }
  console.log("findManyParams", findManyParams);
  const tagsByLabelResult = await db.tag.findMany(findManyParams);
  console.log("tagsByLabelResult", tagsByLabelResult);
  return tagsByLabelResult;
};

If I search for 'mex', I see:

    findManyParams {
      where: { userId: 1, title: { contains: 'mex' } },
      orderBy: { title: 'asc' }
    }
    tagsByLabelResult [
      {
        id: 9,
        title: 'mex',
        description: 'Mexican food',
        userId: 1,
        createdAt: 2020-05-03T22:16:09.134Z,
        modifiedAt: 2020-05-03T22:16:09.134Z
      }
    ]

And for an empty query, tagsByLabelResult contains all tag records.

How can I adjust my tagsByLabel function to aggregate (using "group by") the records and output a "count" for each record of tagsByLabelResult in order by count descending?

    tagsByLabelResult [
      {
        id: 9,
        title: 'mex',
        description: 'Mexican food',
        count: 25,
        userId: 1,
        createdAt: 2020-05-03T22:16:09.134Z,
        modifiedAt: 2020-05-03T22:16:09.134Z
      }
    ]

I see the docs example of prisma.user.count(), but that seems to retrieve a simple count of the result of the whole query rather than a count as a field with a "group by".

I'm using RedwoodJs, Prisma 2, Apollo, GraphQL.

2

There are 2 best solutions below

1
On BEST ANSWER

As of now groupBy support is still in spec here so currently you would only be able to use count with specific querying.

As a workaround, you would have to use prisma.raw for the timebeing.

2
On

In my tags.sdl.js I needed to add:

type TagCount {
  id: Int!
  title: String!
  count: Int!
  principles: [Principle]
  description: String
  createdAt: DateTime!
  modifiedAt: DateTime!
}

And change query tagsByLabel(searchTerm: String): [Tag!]! to tagsByLabel(searchTerm: String): [TagCount!]!

In my TagsAutocomplete.js component, I now have:

export const TagsAutocomplete = ({ onChange, selectedOptions, closeMenuOnSelect }) => {
  const state = {
    isLoading: false,
  };

  const client = useApolloClient();

  const promiseOptions = useCallback(
    async (searchTerm) => {
      try {
        const { data } = await client.query({
          query: QUERY_TAGS_BY_LABEL,
          variables: { searchTerm },
        });

        console.log("promiseOptions data", data);
        const tags = data.tags.map((tag) => {
          if (!tag.label.includes("(")) {
            //ONEDAY why does the count keep getting appended if this condition isn't checked here?
            tag.label = tag.label + " (" + tag.count + ")";
          }
          return tag;
        });
        console.log("promiseOptions tags", tags);
        return tags;
      } catch (e) {
        console.error("Error fetching tags", e);
      }
    },
    [client]
  );
};

And in my tags.js service, I now have:

export const tagsByLabel = async (params) => {
  let query = `
      SELECT t.*, COUNT(pt.B) as count FROM tag t LEFT JOIN _PrincipleToTag pt ON t.id = pt.B WHERE t.userId = ${userIdFromSession} `;

  if (params) {
    const { searchTerm } = params;
    if (searchTerm) {
      query += `AND t.title LIKE '%${searchTerm}%' `;
    }
  }
  query += "GROUP BY t.id ORDER BY count DESC, t.title ASC;";
  console.log("query", query);
  const tagsByLabelResult = await db.raw(query);
  //TODO get secure parameterization working
  console.log("tagsByLabelResult", tagsByLabelResult);
  return tagsByLabelResult;
};

But, as mentioned in the comment, I'm still trying to figure out how to get secure parameterization working.