【问题标题】:How to apply where clause on nested queries in graphQl/Sequelize?如何在 graphQl/Sequelize 中的嵌套查询上应用 where 子句?
【发布时间】:2021-08-12 13:39:08
【问题描述】:

我有以下嵌套结构的菜单模型:

const typeDefs = gql`
  …   
type Menu{
        id:Int
        label: String
        children: [Menu]
        icon: String
        table: String
    }
…

这个模型解析如下:

const resolvers = {
…
   Query: {
      nodes: async (_, args,context) =>{
        try{
…
            const menu=await Menu.findAll({ where: args});
                    return menu;
            } catch(error){
                console.error("ERROR");
                return {};
            }
        },
…
    Menu: {
        children: async(menu) => {
            const getM=await menu.getMenus();
            return getM;
        },
    },  
…

它按要求工作,直到我需要对菜单访问施加一些限制。 让我们考虑一下我想限制对菜单的 id #5 的访问。以下内容适用于第一级,但不适用于儿童。

const menu=await Menu.findAll({ where: {...args,[Op.not]:{id:5}}});

我知道getMenus()是Sequelize直接执行的,不调用resolver,但是如何给children应用“where子句”或者如何让getMenus()考虑“where子句”的约束?

【问题讨论】:

    标签: graphql sequelize.js where-clause nested-query


    【解决方案1】:

    您需要使用 include 来包含子项(菜单)并在其中添加 where 子句。像这样:

    const result: ParentEntity = await ParentEntity.schema(tenant).findAll<ParentEntity>({
            include: [{
              model: ChildEntity.schema(tenant),
              where: yourConditionOnTheChildEntity
            }]
          });
    

    【讨论】:

    • 感谢您的回答。然而它没有用。实际上,它仍然只作用于第一层,同时添加了孩子存在的约束并验证了 where 子句。
    猜你喜欢
    • 1970-01-01
    • 2017-08-27
    • 2016-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多