我想在Sequelize中以多对多关系从连接表中选择ID,并根据其中一个端点限制结果。例如:
ModelA:
- id
- deleted_at
- is_expired
ModelB:
- id
- deleted_at
- is_active
ModelAToModelB:
- a_id
- b_id
我想做点什么
SELECT id FROM ModelAToModelB ab INNER JOIN ModelB b ON ab.b_id = b.id WHERE ab.id = someA_ID AND b.deleted_at IS NULL;
我目前正在做类似
的事情const ModelB = require("./modelb")
const ModelAToModelB = require("./modelatob");
ModelAToModelB.findAll({
where: { id: someA_ID },
include: [
{
model: ModelB,
where: { deleted_at: null }
}
]
})
这似乎有效,除此之外我还可以获得ModelB
的所有数据,当我想要的只是ModelAToB.id
时。
有没有办法废弃ModelB
的数据?或者可以使用ModelA
中的某些内容来获取关联ID?
答案 0 :(得分:0)
const ModelB = require("./modelb")
const ModelAToModelB = require("./modelatob");
ModelAToModelB.findAll({
where: { id: someA_ID },
include: [
{
model: ModelB.scope(null), //Prevent the default scope from adding attributes
where: { deleted_at: null },
required: true, //Force an inner join
attributes: [] //Join without selecting any attributes
}
]
})