Harry
Harry

Reputation: 13329

Sequelize and Graphql reverse lookup

I have two Models:

River.associate = models => {
  River.hasMany(models.Fish, { as: 'Fishes' });
};

Fish.associate = models => {
  Fish.belongsTo(models.River);
};

type River {
    id: ID!
    name: String!
    alternative: String!
    geojson: JSON
    fishes: [Fish]
}

type Fish {
  id: ID!
  name: String!
}

How would I findAll Rivers given a list of Fish ID's? Im not sure how the query must look for this for graphql and sequelize?

type Query {
  river(id: ID!): River
  **rivers(fishIds: ARRAY): River ??????**
  fishes: [Fish]
}

Query: {
rivers: (_, { fishIds }) => {
      return River.findAll({
        where: {
          fishes: fishIds
        }
      });
    },
}

Upvotes: 0

Views: 510

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84867

You can specify WHERE clauses for each of the models you include. Moreover, doing so will convert the eager load to an inner join (which is what you want), unless you explicitly set the required param to false.

That means you should be able to do something like:

River.findAll({ include:
  [
    {
      model: Fish,
      where: { id: fishIds }
    },
  ],
})

Upvotes: 1

Related Questions