续集查询子项的位置



我有一个用户和国家模型。用户属于许多国家,反之亦然。 如何查询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
},
],
});

由于您希望任何用户具有特定的国家/地区,因此没有任何东西可以放入用户的 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
}
},
],
});