简体   繁体   中英

Select and join with sequelize

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

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

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