首页 文章

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

提问于
浏览
0

我想在Sequelize中以多对多关系从连接表中选择ID,并根据其中一个 endpoints 限制结果 . 例如:

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
    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
           }
        ]
    })
    

相关问题