简体   繁体   中英

Sequelize many to many relationship with same instance

I have users and i wantk to implements adding friends. So this creates a many to many relationship, how can i create a many to many relationship with sequelize when using the same instance?

User.belongsToMany(User, {as: "friends", through: "friends})

but i can't figure out how to do with the foreign keys and what they are going to be called

Below example using "sequelize": "^5.21.3" :

import { sequelize } from '../../db';
import { Model, DataTypes, BelongsToManyAddAssociationMixin } from 'sequelize';

class User extends Model {
  public getFriends!: BelongsToManyAddAssociationMixin<User, string>;
}
User.init(
  {
    name: DataTypes.STRING,
  },
  { sequelize, modelName: 'users' },
);

User.belongsToMany(User, { as: 'friends', through: 'user_friends' });

(async function test() {
  try {
    await sequelize.sync({ force: true });
    // seed
    const friendsOfUser1 = [{ name: 'james' }, { name: 'elsa' }];
    const friendsOfUser2 = [{ name: 'jane' }, { name: 'mike' }];
    await User.bulkCreate(
      [
        { name: 'jeremy', friends: friendsOfUser1 },
        { name: 'lynne', friends: friendsOfUser2 },
      ],
      { include: [{ model: User, as: 'friends' }] },
    );
    const jeremy = await User.findOne({ where: { name: 'jeremy' } });
    const firendsOfJeremy = await jeremy.getFriends();
    console.log(firendsOfJeremy);
  } catch (error) {
    console.log(error);
  } finally {
    await sequelize.close();
  }
})();

It will create the table user_friends which stores the ids of the objects. Check the data records in the database:

node-sequelize-examples=# select * from user_friends;
 userId | friendId
--------+----------
      1 |        3
      1 |        4
      2 |        5
      2 |        6
(4 rows)

node-sequelize-examples=# select * from users;
 id |  name
----+--------
  1 | jeremy
  2 | lynne
  3 | james
  4 | elsa
  5 | jane
  6 | mike
(6 rows)

You can call userInstance.getFriends() to get some user's friends.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM