如果我有一个“Users”表和一个“Followings”表(“Followings”有 UserId 和 FollowedId,两者都引用“Users”表中的用户)
“关注”基本上是指一个用户“关注”另一用户
如何设置关联,以便当我使用关注模型查询并包含用户模型时,它将包含两个列的嵌套信息?
示例:
Users
| id | name | email | etc |
Followings
| id | UserId | FollowedId |
UserId 和 FollowedId 均与“用户”表中的用户相关联。
我尝试过这个:
User.hasMany(Following);
Following.belongsTo(User, {foreignKey: 'FollowedId'});
Following.belongsTo(User, {foreignKey: 'UserId'});
但是当我使用时:
Followings.find({
include: User
})
它只会在 UserId 上嵌套信息,而不是在 FollowedID 用户上嵌套信息。
如果这令人困惑,请提问,谢谢!
编辑:使用 PostgreSQL
最佳答案
我认为,如果您为 belongsTo
指定名称,则可以在包含中指定关系。所以类似:
User.hasMany(Following);
Following.belongsTo(User, {foreignKey: 'FollowedId', as: 'Followee'});
Following.belongsTo(User, {foreignKey: 'UserId', as: 'User'});
包含如下内容:
Followings.find({
include: [
{ model: User, as: 'Followee' },
{ model: User, as: 'User' },
]
})
关于javascript - Sequelize - 两个 ID 上的双连接表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26598409/