Sequelize - double joining table on two IDs

只谈情不闲聊 提交于 2019-12-11 11:40:50

问题


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

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?

Example:

Users
| id | name | email | etc |

Followings
| id | UserId | FollowedId |

UserId and FollowedId are both assciated to users on "Users" table.

I tried this:

User.hasMany(Following);
Following.belongsTo(User, {foreignKey: 'FollowedId'});
Following.belongsTo(User, {foreignKey: 'UserId'});

But when I use:

Followings.find({
  include: User
})

It will only nest information on the UserId and not the FollowedID user.

Please ask questions if this is confusing, thanks!

EDIT: using PostgreSQL


回答1:


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'});

With the include like:

Followings.find({
  include: [
    { model: User, as: 'Followee' },
    { model: User, as: 'User' },
  ]
})


来源:https://stackoverflow.com/questions/26598409/sequelize-double-joining-table-on-two-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!