2017-05-05 84 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 
     } 
    ] 
})