SequelizeJS - hasMany to hasMany on the same table with a join table

瘦欲@ 提交于 2020-01-01 03:35:09

问题


My problem is quite simple:

I got a table named users. Those users can have a lot of contacts. Those contacts are other users.

So I have a table named userHasContacts, with the id of the owner (userID), and the id of the contact (contactID).
Both of those foreign keys are referencing users table.

Here is my beautiful diagram:

              ----------------  
______________|____      ____|____
| userHasContacts |      | users |
-------------------      ---------
| #userID         |      | id    |
| #contactID      |      ---------
-------------------          |
              |              |
              ----------------

In sequelize, in my logic, I would write:

Users.hasMany(Users, {foreignKey: 'userID', joinTableName: 'userHasContacts'} );
Users.hasMany(Users, {as: 'Contacts', foreignKey: 'contactID', joinTableName: 'userHasContacts'} );

But it seems like it doesn't work this way, and it's been 2 hours I am trying several ways to write this relation...

The only line that worked for me was

Users.hasMany(UserHasContacts, {foreignKey: 'contactID', joinTableName: 'userHasContacts'} );

UserHasContacts.findAndCountAll({ where: {userID: id} }).success( function(result) {        
    res.json(result);
});

But then I cannot join users table in my find query (via Eager loading) and it simply returns the data inside userHasContacts.

If anyone got an hint, you are welcome!
Thanks by advance !


回答1:


Since what you are trying to do is a self association you only need to call hasMany once, which will create a junction table

User.hasMany(User, { as: 'Contacts', joinTableName: 'userHasContacts'})

Which will create the userHasContacts table as:

CREATE TABLE IF NOT EXISTS `userHasContacts` (`userId` INTEGER , `ContactsId` INTEGER , `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`userId`,`ContactsId`)) ENGINE=InnoDB;

To find users and their contacts you can then do:

User.find({ where: ..., include: [{model: User, as: 'Contacts'}]})


来源:https://stackoverflow.com/questions/18950886/sequelizejs-hasmany-to-hasmany-on-the-same-table-with-a-join-table

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