【问题标题】:Apollo GraphQl model attribute is not accessing object in ReactJsApollo GraphQl 模型属性未访问 ReactJs 中的对象
【发布时间】:2020-10-13 16:52:02
【问题描述】:

我正在使用 Apollo GraphQl Query 在 ReactJs 中实现类别和子类别显示。

我尝试使用与 category 相同的表和字段。 ID, 分类名称, category_img, category_parent_id(同一张表的id), 类别状态,

typeDefs 和解析器如下

Category.js

const typeDefs = gql`
  extend type Query {
    getSingleCategory(id: ID): allCategory
  }
`;
type allCategory {
    id: ID!
    category_name: String
    category_img: String
    category_parent_id: Int
    category_status: Status
 }

const resolvers = {
  Query: {
   getSingleCategory: async (parent, args, context, info) => {
   var data = await db.category.findOne({
     where: {
        id: args.id,
      },
      include: [
        {
          model: db.category,
          as: "children",
          attributes: [["category_name", "children_name"]],
          nested: true,
          required: false,
        },
      ],
      required: false,
    });
    return data;
 },
},
},

GraphQl 中的模型

module.exports = function (sequelize, DataTypes) {
  var category = sequelize.define(
    "category",
    {
      id: {
        type: DataTypes.INTEGER(10).UNSIGNED,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
      },
      category_name: {
        type: DataTypes.STRING(256),
        allowNull: false,
      },
      category_img: {
        type: DataTypes.STRING(256),
        allowNull: false,
      },
      category_parent_id: {
        type: DataTypes.INTEGER(10).UNSIGNED,
        allowNull: false,
        references: {
          // WorkingDays hasMany Users n:n
          model: "category",
          key: "children",
        },
      },
      category_status: {
        type: DataTypes.ENUM("Acitve", "Inactive"),
        allowNull: false,
      },
    },
    {
      tableName: "category",
      timestamps: false,
    }
  );
  category.associate = function (models) {
    models.category.belongsTo(models.category, {
      onDelete: "CASCADE",
      foreignKey: "category_parent_id",
      as: "children",
      targetKey: "id",
    });
  };
  return category;
};

在 ReactJs 中 category.ts

export const GET_CATEGORYBY_ID = gql`
  query($catId: ID!) {
    getSingleCategory(id: $catId) {
      id
      category_name
      category_img
      category_parent_id
      category_status
    }
  }
`;

我正在尝试访问 {data.getSingleCategory},我获得了所有参数,但无法从与 parent_name 相同的表中获取 children_name。

任何人都可以告诉我是什么问题我无法从同一个表中访问该 children_name 作为属性或者有任何其他方式,以便我们可以从同一个表中访问类别/子类别并将其显示到 reactjs 模板。

【问题讨论】:

    标签: reactjs graphql react-apollo apollo-client apollo-server


    【解决方案1】:

    未在类型中[单独]定义,未在父类型中使用/定义为[作为“子”属性?],未在查询中请求...只是从响应中过滤掉。

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2020-05-20
      • 2020-07-06
      • 2019-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-03
      • 2021-06-04
      • 1970-01-01
      相关资源
      最近更新 更多