繁体   English   中英

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

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

我有这个 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;
};

如果我搜索“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
      }
    ]

对于空查询, tagsByLabelResult包含所有标签记录。

如何调整我的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
      }
    ]

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

我正在使用 RedwoodJs、Prisma 2、Apollo、GraphQL。

到目前为止groupBy支持仍然在规范中因此目前您只能使用count进行特定查询。

作为一种解决方法,您必须暂时使用prisma.raw

在我的tags.sdl.js我需要添加:

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

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

在我的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]
  );
};

在我的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;
};

但是,正如评论中提到的,我仍在试图弄清楚如何让安全参数化工作。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM