问题
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