我正在使用 nodejs
和 sequelize
创建 REST API,并且我有 2 个表:
- 用户表
- 好友表
与
/api/friends
我获取了我所有的 friend 列表(存储在我的 friend 表中),但我不知道如何获取他们的名字(从用户表中)。
这是我获取好友列表的请求:
models.Friend.findAll({
where: {
$or: [{
UserID: userFound.id
},
{
idFriend: userFound.id
}],
status : "active"
}
})
如何在我的请求中获取 friend 的姓名?
更新 这是我的用户模型
'use strict';
module.exports = (sequelize, DataTypes) => {
var User = sequelize.define('User', {
email: DataTypes.STRING,
username: DataTypes.STRING,
password: DataTypes.STRING,
isAdmin: DataTypes.BOOLEAN,
isOut: DataTypes.BOOLEAN,
bio: DataTypes.STRING
}, {});
User.associate = function(models) {
// associations can be defined here
models.User.hasMany(models.Message)
models.User.hasMany(models.Friend)
};
return User;
};
这是我 friend 的模型
'use strict';
module.exports = (sequelize, DataTypes) => {
var Friend = sequelize.define('Friend', {
UserID: DataTypes.INTEGER,
idFriend: DataTypes.INTEGER,
status: DataTypes.STRING
}, {});
Friend.associate = function(models) {
// associations can be defined here
models.Message.belongsTo(models.User, {
foreignKey:{
allowNull: false
}
})
};
return Friend;
};
and my get friends function
showFriend: function (req, res) {
var headerAuth = req.headers['authorization'];
var UserId = jwtUtils.getUserId(headerAuth);
// Params
asyncLib.waterfall([
function (done) {
models.User.findOne({
where: { id: UserId }
})
.then(function (userFound) {
done(null, userFound);
})
.catch(function (err) {
return res.status(500).json({ 'error': 'unable to verify user' });
});
},
function (userFound, TargetFound, done) {
models.Friend.findAll({
where: {
$or: [{
UserID: userFound.id
},
{
idFriend: userFound.id
}],
status : "active"
}
})
.then(function (friends) {
if (friends) {
res.status(200).json(friends);
} else {
res.status(404).json({ "error": "no friends found" });
}
})
.catch(function (err) {
return res.status(500).json({ 'error': 'cannot find Friend' })
})
}
], function (newFriend) {
if (newFriend) {
return res.status(201).json({
'newFriend': newFriend.id
})
} else {
return res.status(500).json({ 'error': 'cannot add Friendss' })
}
});
},
谢谢
最佳答案
如果 Friend
和 Users
关联,那么您必须在查询中包含
它们:
models.Friend.findAll({
where: {
$or: [
{ UserID: userFound.id },
{ idFriend: userFound.id }
],
status : "active"
},
include: [{
model: models.User
}]
})
那么你应该能够执行以下操作:
const friends = models.Friend.findAll({ ... })
friends.forEach((friend) => {
/* depends on your Naming Strategy, I'm assuming
`Users` will load as property 'User' on `Friends`,
it depends on how your models and associations are defined
*/
console.log(friend.User.username)
})
关于javascript - 从 Rest API 中的 Sequelize 获取用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49846636/