简体   繁体   English

如何在 Prisma 2 中使用“count”和“group by”?

[英]How can I use “count” and “group by” in Prisma 2?

I have this function which works:我有这个 function 有效:

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:如果我搜索“mex”,我会看到:

    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.对于空查询, tagsByLabelResult包含所有标签记录。

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?如何调整我的tagsByLabel function 以聚合(使用“分组依据”)记录和 output 每个tagsByLabelResult记录的“计数”按计数降序排列?

    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".我看到了prisma.user.count()文档示例,但这似乎检索了整个查询结果的简单计数,而不是作为具有“分组依据”的字段的计数。

I'm using RedwoodJs, Prisma 2, Apollo, GraphQL.我正在使用 RedwoodJs、Prisma 2、Apollo、GraphQL。

As of now groupBy support is still in spec here so currently you would only be able to use count with specific querying.到目前为止groupBy支持仍然在规范中因此目前您只能使用count进行特定查询。

As a workaround, you would have to use prisma.raw for the timebeing.作为一种解决方法,您必须暂时使用prisma.raw

In my tags.sdl.js I needed to add:在我的tags.sdl.js我需要添加:

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

And change query tagsByLabel(searchTerm: String): [Tag!]!并更改查询tagsByLabel(searchTerm: String): [Tag!]! to tagsByLabel(searchTerm: String): [TagCount!]!tagsByLabel(searchTerm: String): [TagCount!]!

In my TagsAutocomplete.js component, I now have:在我的TagsAutocomplete.js组件中,我现在有:

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:在我的tags.js服务中,我现在拥有:

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.但是,正如评论中提到的,我仍在试图弄清楚如何让安全参数化工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在prisma.yml中设置“cluster”属性 - How to set the “cluster” property in prisma.yml 如何使用Apollo / GraphQL递增/递进查询数据源? - How can I use Apollo/GraphQL to incrementally/progressively query a datasource? 如何在阿波罗客户端缓存中使用“模式”? - How can I use `schema` in apollo client cache? 如何使用 useQuery 钩子填充其他钩子中的状态? - How can I use the useQuery hook to populate state in other hooks? 如何将 Apollo 的 cacheRedirect 与嵌套查询一起使用 - How can I use Apollo's cacheRedirect with a nested query 如何在react-apollo graphql查询中正确使用动态变量? - How Can I correctly use dynamic variables in react-apollo graphql query? 我该如何收听订阅,并且在收到内容时使用缓存将其保存? - How can I listen to a Subscription and when recieving something, use the cache to save it? 如何在另一个查询完成后进行graphql查询并将其数据用作变量? - How can I make a graphql query after another query is finish and use its data as variable? 如何使用提供者值来 useMutation 并在之后将更改分派到状态? - How can I use a provider value to useMutation and also dispatch the changes to state afterwards? 我可以使用HOC使用graphql和redux包装组件吗 - Can I use HOC to wrap component with graphql and redux
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM