在不选择的情况下续订连接表

时间:2017-05-05 02:03:26

标签: javascript orm sequelize.js

我想在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?

1 个答案:

答案 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
       }
    ]
})
相关问题