Sequelize和Graphql反向查找

时间:2018-06-19 18:00:58

标签: express sequelize.js graphql apollo-server

我有两个模型:

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!
}

如何查找给出了鱼类ID列表的所有河流?我不确定查询必须如何为graphql和续集查找该

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

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

1 个答案:

答案 0 :(得分:1)

您可以为包含的每个模型指定WHERE子句。此外,除非将required参数明确设置为false,否则这样做会将急切的负载转换为内部联接(这是您想要的)。

这意味着您应该可以执行以下操作:

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