Reputation: 2599
I´m new to sequelize and trying to determine how to perform a query on a belongstomany relationship, where I need to check for the existence of the child relationship but I don´t want to bring any of its fields.
Project.belongsToMany(models.User, {
through: 'userproject', as: 'links', foreignKey: 'project_id', otherKey: 'user_id'
});
My attempt:
const linkedProjects = this.model.findAll({
attributes: ['Project.*'],
include: [{
model: models.User,
as: 'links',
where: {
userid: user.sub
}
}]
});
However this stil brings me the projected links data, which is useless for me except for the where part.
What´s the best way to accomplish that without a "raw query" ? I´m looking for, basically:
select p.* from project p
inner join userproject up on p.project_id = up.project_id
inner join user u on up.user_id = u.id
where u.userid = 'xxx'
Upvotes: 0
Views: 2448
Reputation: 51
In a BelongsToMany fetching with sequelize's finders (findAll, findOne...), you can use the
through: {
attributes: ['created_at']
}
For specify those fields to show in the child record.
Upvotes: 0
Reputation: 1734
Re-iterating for marking it as a solution.
The solution is to add attributes: []
to retrieve no columns in the sequelize operation. The attributes field is an array containing column names which have to be retrieved while executing the sequelize operation.
const linkedProjects = this.model.findAll({
attributes: ['Project.*'],
include: [{
model: models.User,
as: 'links',
attributes: [],
where: {
userid: user.sub
}
}]
});
Upvotes: 1
Reputation: 58523
Instead of this :
attributes: ['Project.*'], // this will load only fields from project table
Use
this.model.findAll({
attributes: ['id','title',...], // all the attributes from project table
include: [{
model: models.User,
attributes: ['id','project_id' ,], // all the attributes from user table
as: 'links',
where: {
userid: user.sub
}
}]
});
//OR
// remove attributes from all
this.model.findAll({
include: [{
model: models.User,
as: 'links',
where: {
userid: user.sub
}
}]
});
Upvotes: 0