Ad

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.

Ad

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.

Ad
source: stackoverflow.com
Ad