mickhansen / graphql-sequelize

GraphQL & Relay for MySQL & Postgres via Sequelize
MIT License
1.9k stars 172 forks source link

How to express two way relationship #700

Closed MaximilianLloyd closed 3 years ago

MaximilianLloyd commented 3 years ago

Hi! First off thank youy for creating this library.

I was wondering how one would express a two way relationship like this. I want it to be possible to list the Stocks for each market. But also get the associated market, like you can do in sequelize. Seeing as one needs to be defined before the other, how would you go about implementing it in the example I posted?

image

I found this solution, but I'm not sure it's the best approach.

const baseStockType = new GraphQLObjectType({
  name: 'MarketStocks',
  description: 'A stock',
  fields: attributeFields(Stock),
});

const marketType = new GraphQLObjectType({
  name: 'Market',
  description: 'Markets',
  fields: {
    ...attributeFields(Market),
    stocks: {
      type: new GraphQLList(baseStockType),
      resolve: resolver(Market.Stock),
    },
  },
});

Thank you if you take the time to read this.

mickhansen commented 3 years ago

fields can be a function, letting you use require inside to avoid cyclical dependency issues.

MaximilianLloyd commented 3 years ago

Makes sense. Thanks a lot!