Sequelize - double joining table on two IDs(Sequelize - 两个 ID 上的双重连接表)
问题描述
如果我有一个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 上的双重连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Sequelize - 两个 ID 上的双重连接表


- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- addEventListener 在 IE 11 中不起作用 2022-01-01