Many-to-many Relationships Within GraphQL Apollo
As I start to flesh out my first GraphQL backend, I'm running into an issue with how to handle Many-to-Many models in schemas and resolvers whenever pivot tables are needed.
Say I have Users and Teams. Each of them belongsToMany in a pivot table called UserTeam. The question is how best to handle the data flow with resolvers.
Now I could handle this by creating a schema for the pivot table and connecting the resolver relationships to that. But it seems so messy. If I do that, queries will end up such as:
query{
user(ID: "1"){
userTeams(){
team{
name
}
}
}
}
Now there has to be a better way to do this. I just don't know what it is.
Answer
Sequelize supports belongsToMany associations that allow you to query the associated model through another table/model. This is what's commonly used for M2M relationships, at least when you don't need any data from the pivot table itself. For example defining a relationship like:
User.belongsToMany(Team, {through: 'UserTeam'})
will let you call the appropriate method on a returned instance:
user.getTeams()
Similarly, associated models may be included when using a find method:
User.findOne({ include:[Team] })
See the docs more details.
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error