Home > database >  Select and join with sequelize
Select and join with sequelize

Time:11-25

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

CodePudding user response:

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})
       }) 
  • Related