Sequelize - 两个 ID 上的双重连接表 [英] Sequelize - double joining table on two IDs

查看:11
本文介绍了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 上的双重连接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆