繁体   English   中英

Select 并加入续集

[英]Select and join with sequelize

如何用续集制作这段代码?

我使用了包含,但它带来了所有用户数据,但我只需要名称

select comments.comment, users.name from comments inner join users on comments.userId = users.id

我的代码:

Comments.findAll({
       where: {
           projectId: id
       },
       include:  User
   }).then(response =>{
      
           res.json({comments: response})
       }) 

如果您只想减少User model 属性,则只需在attributes选项中指明所需的属性:

Comments.findAll({
       where: {
           projectId: id
       },
       include:  [{ 
         model: User,
         attributes: ['name']
       }]
   }).then(response =>{
      
           res.json({comments: response})
       }) 

如果您想将用户名添加为与所有Comments字段相同级别的字符串属性,只需在Comments model 的attributes选项中使用所需的别名进行指示:

Comments.findAll({
       where: {
           projectId: id
       },
       attributes: [[Sequelize.col('Users.name'), 'userName']],
       include:  [{ 
         model: User,
         attributes: []
       }]
   }).then(response =>{
      
           res.json({comments: response})
       }) 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM