问题描述
如果我有一个Users"表和一个Followings"表(Followings"有 UserId 和 FollowedId,都指Users"表中的用户)
If I have a "Users" table and a "Followings" table ("Followings" has UserId and FollowedId, both refer to users on the "Users" table)
关注"基本上是指一个用户关注"另一个用户
"Followings" is basically when one user "follows" another user
如何设置关联,以便当我使用 Follows 模型查询和包含 Users 模型时,它将包含 BOTH 列的嵌套信息?
How do I set up the associations so that when I use the Followings Model to query and include the Users model, it will include nested info for BOTH columns?
例子:
Users
| id | name | email | etc |
Followings
| id | UserId | FollowedId |
UserId 和 FollowedId 都与Users"表中的用户相关联.
UserId and FollowedId are both assciated to users on "Users" table.
我试过了:
User.hasMany(Following);
Following.belongsTo(User, {foreignKey: 'FollowedId'});
Following.belongsTo(User, {foreignKey: 'UserId'});
但是当我使用时:
Followings.find({
include: User
})
它只会在 UserId 上嵌套信息,而不是 FollowedID 用户.
It will only nest information on the UserId and not the FollowedID user.
如果这令人困惑,请提出问题,谢谢!
Please ask questions if this is confusing, thanks!
使用 PostgreSQL
using PostgreSQL
推荐答案
我认为如果你给 belongsTo 一个名字,你可以在你的包含中指定关系.所以像:
I think if you give a name to the belongsTo you can specify the relationship in your include. So something like:
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' },
]
})
这篇关于Sequelize - 两个 ID 上的双重连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)