Search code examples
react-apolloprismaprisma-graphqlredwoodjs

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


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.


Solution

  • 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.