简体   繁体   中英

Sequelize join table without selecting

I'd like to select IDs from a join table in a many-to-many relation in Sequelize, and restrict results based on one of the endpoints. For example:

ModelA:
- id
- deleted_at
- is_expired

ModelB:
- id
- deleted_at
- is_active

ModelAToModelB:
- a_id
- b_id

I'd like to do something like

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;

I'm currently do something like

const ModelB = require("./modelb")
const ModelAToModelB = require("./modelatob");

ModelAToModelB.findAll({
    where: { id: someA_ID },
    include: [
       {
           model: ModelB,
           where: { deleted_at: null }
       }
    ]
})

That seems to work, except then I also get all the data from ModelB as well, when all I want is ModelAToB.id .

Is there any way to scrap ModelB 's data? Or maybe use something from ModelA to get just the association IDs?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM