简体   繁体   中英

Graphql custom defined join

I have the following tables defined using sequelize for a js based graphql server (shortened for brevity, and omitting a number of other entities)

const MetaData = sequelize.define(
  "MetaData",
  {
    MetaID: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    EntityID: {
        type: Sequelize.INTEGER
    },
    EntityType: {
        type: Sequelize.STRING
    },
    MetaKey: {
        type: Sequelize.STRING
    },
    MetaValue: {
        type: Sequelize.STRING
    }
  }
);
const Staff = sequelize.define(
  "staff",
  {
    staffID: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    email: {
        type: Sequelize.STRING
    },
    firstName: {
        type: Sequelize.STRING
    },
    lastName: {
        type: Sequelize.STRING
    }
  }
);
const Person = sequelize.define(
  "Person",
  {
    personID: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    firstName: Sequelize.STRING,
    lastName: Sequelize.STRING
  }
);

A sample of the metadata table is

[{
 EntityID: 5,
 EntityType: "Staff",
 MetaKey: "Active",
 MetaValue: "true"
},{
 EntityID: 5,
 EntityType: "Person",
 MetaKey: "HairColor",
 MetaValue: "Blue"
}]

Is there a way, either in graphql or sequelize , to create a query that will return the meta data associated with the requested type? Would a custom resolver be able to solve this solution without making a crazy amount of extra calls?

For example, when I request a staff member, I want to be able to receive all associated metadata.

EDIT: Per the sequelize docs on polymorphic associations I added the following but it is not returning the data

Staff.MetaData = Staff.hasMany(MetaData, {
  foreignKey: 'EntityID',
  constraints: 'false',
  scope: {
      EntityType: 'Staff'
  }
});
MetaData.belongsTo(Staff, {
  foreignKey: 'EntityID',
  constraints: false,
  as: 'Staff'
});

MetaData.getItem = function () {
  return this['get' + this.get('EntityType')]();
};

It turns out I was missing a call in my resolvers.js

Staff: {
  MetaData: resolver(Staff.MetaData)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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