Select 并加入 sequelize
Select and join with sequelize
如何用sequelize制作这段代码?
我用了include,但它带来了所有的用户数据,但我只需要名字
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
模型属性,那么只需在 attributes
选项中指明需要的属性:
Comments.findAll({
where: {
projectId: id
},
include: [{
model: User,
attributes: ['name']
}]
}).then(response =>{
res.json({comments: response})
})
如果您想将用户名添加为与所有 Comments
字段相同级别的字符串道具,只需在 Comments
模型的 attributes
选项中用所需的别名:
Comments.findAll({
where: {
projectId: id
},
attributes: [[Sequelize.col('Users.name'), 'userName']],
include: [{
model: User,
attributes: []
}]
}).then(response =>{
res.json({comments: response})
})
如何用sequelize制作这段代码?
我用了include,但它带来了所有的用户数据,但我只需要名字
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
模型属性,那么只需在 attributes
选项中指明需要的属性:
Comments.findAll({
where: {
projectId: id
},
include: [{
model: User,
attributes: ['name']
}]
}).then(response =>{
res.json({comments: response})
})
如果您想将用户名添加为与所有 Comments
字段相同级别的字符串道具,只需在 Comments
模型的 attributes
选项中用所需的别名:
Comments.findAll({
where: {
projectId: id
},
attributes: [[Sequelize.col('Users.name'), 'userName']],
include: [{
model: User,
attributes: []
}]
}).then(response =>{
res.json({comments: response})
})