请求好友表时如何获取2个用户的信息?
我的同 table friend 的格式是这样的:
id X , UserId : 1 , idFriend : 3, ...
我的表 User 的格式如下:
id X , name , mail , ...
当我在查询中链接模型用户时,我只获得了 UserID 的信息,但没有获得 idFriend 的信息
我的要求是
models.Friend.findAll({
where: {
$or: [{
idFriend: userFound.id
},
{
UserID: userFound.id
}],
status: "pending"
},
include: [
{ model: models.User },
]
})
我该怎么做?
最佳答案
1st 在您的 friend 模型中这样定义关联:
Friend.belongsTo(User, { foreignKey : 'UserID', constraints: false});
Friend.belongsTo(User, { as: 'friend', foreignKey : 'idFriend' , constraints:false});
第二件事是像这样包含模型:
models.Friend.findAll({
where: {
$or: [{
idFriend: userFound.id
},
{
UserID: userFound.id
}],
status: "pending"
},
include: [
{
model: models.User ,
required : false,
where : { id : userFound.id }
},{
model: models.User ,
as : 'friend', // <--------- Magic is here
required : false,
where : { id : userFound.id }
}
]
})
关于javascript - 在 sequelize 中访问表用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49956019/