2017-05-05 75 views
0

我想从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
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 
     } 
    ] 
})