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

后端 未结 1 1499
自闭症患者
自闭症患者 2021-02-10 07:11

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

1条回答
  •  孤独总比滥情好
    2021-02-10 07:30

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

    0 讨论(0)
提交回复
热议问题