簡體   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