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
}
]
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With