首页 > 解决方案 > Sequelize 查询 where on children

问题描述

我有一个用户和国家模型。用户属于许多国家,反之亦然。如何查询countries数组中只有特定国家/地区 ID 的用户?

const users = await DB.User.findAll({
  where: {
    // What to put here?
  },
  include: [
    {
      model: DB.Country,
      as: 'countries',
      // Putting where here only causes the countries to filter
    },
  ],
});

标签: postgresqlsequelize.js

解决方案


由于您希望任何用户具有特定的国家/地区,因此无需在用户的 where 子句中放置任何内容,请将 where 子句放在国家/地区包含部分中。

const users = await DB.User.findAll({
  where: {
    // Nothing to put here
  },
  include: [
    {
      model: DB.Country,
      as: 'countries',
      where:{
          id : YOUR_EXPECTED_COUNTRY_ID
      }
    },
  ],
});

推荐阅读