如何在graphQl/Sequelize 中对嵌套查询应用where 子句?

问题描述

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

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;
        },},…

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

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

我知道 getMenus() 是由 Sequelize 直接执行的,没有调用解析器,但是如何为孩子应用“where 子句”或如何让 getMenus() 考虑“where 子句”的约束?

解决方法

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

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