簡體   English   中英

Sequelize - 兩個ID上的雙連接表

[英]Sequelize - double joining table on two IDs

如果我有一個“用戶”表和一個“關注”表(“關注”有UserId和FollowedId,兩者都引用“用戶”表上的用戶)

“跟隨”基本上是當一個用戶“跟隨”另一個用戶時

如何設置關聯,以便在使用Followings Model查詢和包含Users模型時,它將包含BOTH列的嵌套信息?

例:

Users
| id | name | email | etc |

Followings
| id | UserId | FollowedId |

UserId和FollowedId都與“用戶”表中的用戶相關聯。

我試過這個:

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

但是當我使用時:

Followings.find({
  include: User
})

它只會在UserId而不是FollowedID用戶上嵌套信息。

如果這令人困惑,請提出問題,謝謝!

編輯:使用PostgreSQL

我想如果你給belongsTo命名,你可以在include中指定關系。 所以類似於:

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' },
  ]
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM