Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 !

like image 465
Niflhel Avatar asked Sep 23 '13 02:09

Niflhel


1 Answers

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'}]})
like image 191
Jan Aagaard Meier Avatar answered Oct 11 '22 17:10

Jan Aagaard Meier