How to make this code with the sequelize?
I used include, but it brings all the user data but I only need the name
select comments.comment, users.name from comments inner join users on comments.userId = users.id
my code:
Comments.findAll({ where: { projectId: id }, include: User }).then(response =>{ res.json({comments: response}) })
Advertisement
Answer
If you just want to reduce User
model attributes then just indicate needed attributes in the attributes
option:
Comments.findAll({ where: { projectId: id }, include: [{ model: User, attributes: ['name'] }] }).then(response =>{ res.json({comments: response}) })
If you want to add a user’s name as a string prop at the same level as all Comments
fields simply indicate it in the attributes
option of Comments
model with a desired alias:
Comments.findAll({ where: { projectId: id }, attributes: [[Sequelize.col('Users.name'), 'userName']], include: [{ model: User, attributes: [] }] }).then(response =>{ res.json({comments: response}) })