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 上的双重连接表


基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01